如何在没有这个运算符的情况下实现默认运算符<<(ostream&,T)的类型?

How to implement a default operator<<(ostream&, T) for type without this operator?

本文关键字:lt 运算符 类型 ostream 实现 情况下 默认      更新时间:2023-10-16

由于将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;

问题:

  1. 为什么编译器找不到模板函数?
  2. 有没有办法实施一般解决方案?

如果存在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>::valuetrue,则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现在在参数为voidstd::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作为参数的专业化。