我进行了一些浏览,这是最相关的 link我可以找到,但它没有回答我的问题
问题:为什么模板替换失败,以下内容无法编译?
template <typename T>
struct A
{
A() {};
A(T value) : val(value){}
operator T() { return this->val;}
T val;
};
A<std::string> test;
std::cout << "xxx" + std::string(test); //works fine
std::cout << "xxx" + test; //compiler error
错误消息:
error: no match for 'operator+' (operand types are 'const char [4]' and 'A<std::__cxx11::basic_string<char> >')
19 | std::cout << "xxx" + test;
| ~~~~~ ^ ~~~~
| | |
| | A<std::__cxx11::basic_string<char> >
| const char [4]
最佳答案
std::operator+(std::basic_string)
是一组运算符模板,需要对第二个操作数进行模板实参推导test
。但 template argument deduction 中不会考虑隐式转换(从 A<std::string>
到 std::string
) .
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
正如您所展示的,显式转换如 "xxx" + std::string(test);
工作正常。您还可以显式指定模板参数(以丑陋的方式)来绕过模板参数推导。
operator+ <char, std::char_traits<char>, std::allocator<char>>("xxx", test);
关于c++ - 模板转换运算符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68829565/