Reputation: 400
I have done a bit of browsing and this was the most relevant link that I could find, however it does not answer my question
Question: Why does the template substitution fail and the following does not compile?
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 message:
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]
Upvotes: 2
Views: 400
Reputation: 172894
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.
As you have showed, explicit conversion like "xxx" + std::string(test);
works fine. You can also specify template arguments explicitly (in ugly way) to bypass template argument deduction.
operator+ <char, std::char_traits<char>, std::allocator<char>>("xxx", test);
Upvotes: 4