自 std::to_string
添加到 c++11,我开始实现 to_string
而不是更传统的 operator<<(ostream&, T)
.我需要将两者链接在一起,以便合并依赖 operator<<(ostream&, T)
的库.我希望能够表达如果 T 有 operator<<(ostream&, T)
, 用它;否则,使用 std::to_string
.我正在制作一个更有限的版本的原型(prototype),该版本支持 operator<<
对于所有枚举类。
enum class MyEnum { A, B, C };
// plain version works
//std::ostream& operator<<(std::ostream& out, const MyEnum& t) {
// return (out << to_string(t));
//}
// templated version not working
template<typename T,
typename std::enable_if<std::is_enum<T>::value>::type
>
std::ostream& operator<<(std::ostream& out, const T& t) {
return (out << to_string(t));
}
编译器说 error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'MyEnum')
cout << v << endl;
问题:
- 为什么编译器找不到模板函数?
- 有没有办法实现通用解决方案?
最佳答案
如果存在 std::to_string
,以下将起作用接受类型为 const MyEnum
的参数(根据 clang-703.0.31,不存在)。
#include <iostream>
#include <type_traits>
enum class MyEnum { A, B, C };
template<typename T>
typename std::enable_if<std::is_enum<T>::value, std::ostream &>::type
operator<<(std::ostream& out, const T& t) {
return (out << std::to_string(t));
}
int main() {
MyEnum a;
std::cout << a << std::endl;
}
根据docs , 有两种使用方式 std::enable_if
,其中之一是使函数的返回类型仅在T
时有效。是一个枚举类型(在你的例子中)。这就是这段代码所显示的。如果std::is_enum<T>::value
是true
, 然后 std::enable_if<std::is_enum<T>::value, std::ostream &>::type
结果 std::ostream &
否则没有定义(这会让编译器对你大喊大叫)。
你可以可能写类似my::to_string
的东西这也会尝试转换为用户定义的字符串类型:
namespace my {
template<typename T>
typename std::enable_if<! std::is_void<T>{} && std::is_fundamental<T>{}, std::string>::type
to_string(T t) {
return std::to_string(t);
}
std::string to_string(std::nullptr_t) = delete;
std::string to_string(MyEnum a) {
return "This is an enum";
}
}
然后,您可以使用 my::to_string
而不是 std::to_string
在你的operator<<
:
return (out << my::to_string(t));
编辑使用my::to_string
现在当它的参数是 void
时会导致编译错误或 std::nullptr_t
.
为什么你的代码不起作用
查看 docs 中的示例:
// 2. the second template argument is only valid if T is an integral type: template < class T, class = typename std::enable_if<std::is_integral<T>::value>::type> bool is_even (T i) {return !bool(i%2);}
如你所见,第二个模板参数是用class = /* enable_if stuff */
写的,但在您的代码中,您只需执行 template< typename T, /* enable_if stuff */ >
.因此,如果您遵循文档,您将得到正确的结果——编译器会说找不到 std::to_string
的特化。接受了 enum
作为参数。
关于c++ - 如何在没有此运算符的情况下为类型实现默认运算符<<(ostream&, T)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908812/