通用模板ostream的C ++ ambigous重载<<操作者

时间:2015-05-29 13:54:17

标签: c++ templates c++11 ostream enable-if

此问题遵循我之前的问题:Generic operator<< ostream C++ for stringifiable class我希望实现一个通用<<ostream运算符,该运算符适用于拥有to_str()方法的任何类。

由于这个answer,我成功检查了一个类是否实现了to_str()方法并使用std::cout << stringify(a)。但是,我在编写模板ostream<<运算符时难以使std::cout << a有效。

以下测试代码:

#include <iostream>
#include <sstream>
#include <string>

template<class ...> using void_t = void;

template<typename T, typename = void>
struct has_to_string
: std::false_type { };

template<typename T>
struct has_to_string<T, 
    void_t<decltype(std::declval<T>().to_str())>
    >
: std::true_type { };

template<typename T> std::enable_if_t<has_to_string<T>::value, std::string> 
stringify(T t) { 
    return t.to_str(); 
} 

template<typename T> std::enable_if_t<!has_to_string<T>::value, std::string> 
stringify(T t) { 
    return static_cast<std::ostringstream&>(std::ostringstream() << t).str(); 
} 

// The following does not work
/*
template<typename T> std::enable_if_t<has_to_string<T>::value, std::ostream&> 
operator<<(std::ostream& os, const T& t) {
    os << t.to_str();
    return os;
}

template<typename T> std::enable_if_t<!has_to_string<T>::value, std::ostream&> 
operator<<(std::ostream& os, const T& t) {
    os << t;
    return os;
}
*/

struct A {
    int a;
    std::string to_str() const { return std::to_string(a); }
};

struct B {
    std::string b;
    std::string to_str() const { return b; }
};

int main() {
    A a{3};
    B b{"hello"};
    std::cout << stringify(a) << stringify(b) << std::endl;    // This works but I don't want to use stringify
    // std::cout << a << b << std::endl;               // I want this but it does not work
}

给出与原始问题相同的错误。我做错了什么?

1 个答案:

答案 0 :(得分:2)

当类型为std :: string时,运算符&lt;&lt; 错误会出现模糊重载,因为代码中的模板化版本与ostream标头中的模板版本具有相同的优先级

您可以通过以下方式更改测试程序来检查这是您的问题的根源:

int main() {
    std::cout << std::string("There is your problem") << std::endl;
}

你仍然会看到同样的错误。

要解决此问题,您可以添加运算符&lt;&lt;的明确定义这将优先于两个冲突的模板。

std::ostream& operator<<(std::ostream& os, const std::string& t) {
    using std::operator<<;
    os << t;
    return os;
}