通用运算符<<用于stringifiable类的ostream C ++

时间:2015-05-27 16:12:12

标签: c++ templates c++11 ostream

是否可以使用模板化通用<<ostream运算符,该运算符适用于拥有to_string()方法的任何类? 例如,以下代码:

#include <iostream>
#include <string>

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; }
};

template<class Stringifiable>
std::ostream& operator<< (std::ostream& os, const Stringifiable& s) {
    os << s.to_str();
    return os;
}

int main() {
    A a{3};
    B b{"hello"};
    std::cout << a << b << std::endl;
}

无法编译。给出的错误类型为:

prog.cpp: In instantiation of 'std::ostream& operator<<(std::ostream&, const Stringifiable&) [with Stringifiable = A; std::ostream = std::basic_ostream<char>]':
prog.cpp:23:15:   required from here
prog.cpp:16:5: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::string {aka std::basic_string<char>}')
  os << s.to_str();

0 个答案:

没有答案