为什么需要使用std::string::operator+()时明确调用Myclass::operator string()?

5
考虑下面的代码。我不明白为什么我的GCC编译器不会尝试隐式使用Myclass :: operator string(),尽管已经定义了Myclass :: operator string():
#include <string>

using namespace std;

struct T {
};

T operator+(const T& a, const T&b) { }

struct Myclass {
    operator string() const { }
    operator T() const { }
};

int main() {
    T a;
    string b;
    Myclass c;
    c + a;  // OK
    c.operator  string() + b; // OK
    c + b; // Not OK
    /* The above line does not compile, although in <string> I see:
    basic_string<_CharT, _Traits, _Alloc>
    operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
          const basic_string<_CharT, _Traits, _Alloc>& __rhs)
     */
}

2
我相信原因是std::operator+是一个函数模板,而不是一个函数。 - Alexandre C.
1个回答

2
因为字符串操作符是模板,所以它不能被捕获,而其他操作符可以。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接