我目前正试图实现一个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