模板转换运算符问题

Template conversion operator issue

我浏览了一下,这是我能找到的最相关的 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) is a set of operator templates, template argument deduction needs to be performed on the 2nd operand test. But implicit conversion (from A<std::string> to std::string) won't be considered in template argument deduction.

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