我目前正試圖實現一個toString
功能.toString()
或std::to_string()
這取決於可用於推導型SFINAE回退時,函數不存在
到目前爲止,我有這方面的工作片段的呼叫:
#include <iostream>
#include <string>
template <class T>
auto toString(const T& obj)
-> decltype(obj.toString(), std::string())
{
return obj.toString();
}
template <class T>
auto toString(const T& obj)
-> decltype(std::to_string(obj), std::string())
{
return std::to_string(obj);
}
template <class T>
auto toString(const T& obj)
-> decltype(std::string(obj))
{
return std::string(obj);
}
class Foo{
public:
std::string toString() const {
return "Hello";
}
};
int main()
{
Foo bar;
std::cout << toString(bar);
std::cout << toString(5);
std::cout << toString("Hello const char*");
}
現在我想插入一個static_assert
當上面的那些過載沒有可行時,因爲對於較老的GCC版本的默認GCC錯誤消息沒有很多信息。
如何檢查.toString()
和std::to_string()
是否可能用於T
?
到目前爲止,我發現沒有辦法檢查是否不是目前,只有其他的方式。我希望有人有一個想法如何解決這個問題,並感謝您的時間。
'decltype( std :: to_string(obj),std :: string())' - TIL。但是你應該使第一個表達式失效。一個頑皮的用戶超載的逗號運算符可能會搞砸你的SFINAE – StoryTeller
@ max66 - 沒有意義重複自己。而OP的版本可以在修復函數的返回類型的同時處理任何可轉換爲'std :: string'的東西。非常聰明。 – StoryTeller
@StoryTeller - 你是對的。 – max66