在this answer中,我根据类型的is_arithmetic
属性定义一个模板:
template<typename T> enable_if_t<is_arithmetic<T>::value, string> stringify(T t){
return to_string(t);
}
template<typename T> enable_if_t<!is_arithmetic<T>::value, string> stringify(T t){
return static_cast<ostringstream&>(ostringstream() << t).str();
}
dyp suggests,而不是类型的
is_arithmetic
属性,是否为该类型定义to_string
是模板选择标准。这显然是可取的,但我不知道一种说法:If
std::to_string
is not defined then use theostringstream
overload.
声明
to_string
标准很简单:template<typename T> decltype(to_string(T{})) stringify(T t){
return to_string(t);
}
与我无法弄清楚如何构造的标准相反。这显然行不通,但希望它能传达我正在尝试构造的内容:
template<typename T> enable_if_t<!decltype(to_string(T{})::value, string> (T t){
return static_cast<ostringstream&>(ostringstream() << t).str();
}
最佳答案
在上周的委员会 session 上,新投票通过了图书馆基础知识TS:
template<class T>
using to_string_t = decltype(std::to_string(std::declval<T>()));
template<class T>
using has_to_string = std::experimental::is_detected<to_string_t, T>;
然后将
has_to_string
上的dispatch和/或SFINAE标记为您的心脏内容。您可以咨询the current working draft of the TS以了解如何实现
is_detected
和 friend 。它与@Yakk的答案中的can_apply
非常相似。
关于c++ - 元编程:函数定义失败定义了单独的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47821418/