在 这个答案中,我根据类型的 is_arithmetic
属性定义了一个模板:>
In this answer I define a template based on the type's is_arithmetic
property:
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 建议而不是 类型的 is_arithmetic
属性,即是否为类型定义了 to_string
作为模板选择标准.这显然是可取的,但我不知道怎么说:
dyp suggests that rather than the is_arithmetic
property of the type, that whether to_string
is defined for the type be the template selection criteria. This is clearly desirable, but I don't know a way to say:
如果 std::to_string
未定义,则使用 ostringstream
重载.
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);
}
这与我不知道如何构建的标准相反.这显然不起作用,但希望它传达了我正在尝试构建的内容:
It's the opposite of that criteria that I can't figure out how to construct. This obviously doesn't work, but hopefully it conveys what I'm trying to construct:
template<typename T> enable_if_t<!decltype(to_string(T{})::value, string> (T t){
return static_cast<ostringstream&>(ostringstream() << t).str();
}
在上周的委员会会议上新鲜投票进入图书馆基础 TS:
Freshly voted into the library fundamentals TS at last week's committee meeting:
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 标记为您的心意.
Then tag dispatch and/or SFINAE on has_to_string
to your heart's content.
您可以参考TS的当前工作草案is_detected
和朋友是如何实现的.它与@Yakk 的回答中的 can_apply
非常相似.
You can consult the current working draft of the TS on how is_detected
and friends can be implemented. It's rather similar to can_apply
in @Yakk's answer.
这篇关于元编程:函数定义失败定义了一个单独的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!