Metaprograming: Failure of Function Definition Defines a Separate Function(元编程:函数定义失败定义了一个单独的函数)
问题描述
在 这个答案中,我根据类型的 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_stringis not defined then use theostringstreamoverload.
声明 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.
这篇关于元编程:函数定义失败定义了一个单独的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:元编程:函数定义失败定义了一个单独的函数
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
