c++ - 元编程:函数定义失败定义了单独的函数

标签 c++ templates template-meta-programming sfinae result-of

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 the ostringstream 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/

相关文章:

c++ - 很难理解带有 async_read 和 async_write 的 Boost ASIO TCP 的一些概念

c++ - 简单函数的 Unicode 编译器错误

html - Angular 2。如何在模板中打印来自 @Input() 参数的 HTML 标签?

c++ - 格式错误的调用的零长度可变参数扩展

c++ - type_traits 中是否有类似 std::remove_const_reference 的东西

c++ - 在 C++11 中使用模板元编程连接列表

c++ - 为什么允许在 switch 语句中声明变量?但不是声明+初始化?

c++ - 如何解决不合格名称查找问题

c++ - 在 C++ 模板元编程中检测 void 方法

c++ - 编码和读取 ID3 标签