如何在没有这个运算符的情况下实现默认运算符<<(ostream&,T)的类型?
How to implement a default operator<<(ostream&, T) for type without this operator?
由于将std::to_string
添加到C 11中,因此我开始实现to_string
而不是更传统的operator<<(ostream&, T)
。我需要将两者链接在一起,以合并依赖operator<<(ostream&, T)
的库。我想能够表达如果T具有operator<<(ostream&, T)
,请使用它;否则,请使用std::to_string
。我正在制作一个更有限的版本,该版本可用于所有枚举类别。
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不存在的CC_9)。/p>
#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;
}
根据文档,有两种使用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";
}
}
然后,您可以在operator<<
中使用my::to_string
而不是std::to_string
:
return (out << my::to_string(t));
编辑:使用my::to_string
现在在参数为void
或std::nullptr_t
时会导致汇编错误。
为什么您的代码不起作用
查看文档中的示例:
// 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
作为参数的专业化。
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多