为什么不将自动向下转换应用于模板函数?

iBu*_*Bug 7 c++ downcast template-function

有人问这个关于字符串附加的问题.它string s; s = s + 2;没有编译.人们给出了答案,说明operator+被定义为模板函数而operator+=不是,因此不应用自动向下转换(int(2)to char(2)).

原型是

template<typename _CharT, typename _Traits, typename _Alloc>
class basic_string{
    basic_string&
      operator+=(_CharT __c);
};

template<typename _CharT, typename _Traits, typename _Alloc>
  inline basic_string<_CharT, _Traits, _Alloc>
  operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, _CharT __rhs);
Run Code Online (Sandbox Code Playgroud)

为什么编译器不能只使用这个原型并将int(2)转换为char(2)?

basic_string<char, _T, _A> operator+(const basic_string<char, _T, _A>, char);
Run Code Online (Sandbox Code Playgroud)

编译器(G ++ 6.3.0)抱怨说

[Note] deduced conflicting types for parameter '_CharT' ('char' and 'int')
Run Code Online (Sandbox Code Playgroud)

Bau*_*gen 8

关键的区别在于,对于operator +=变体,std::basic_string其RHS 的char类型模板参数已经固定char,而operator+模板必须从其参数中推导出它.

因此,对于这种+=情况,编译器知道你"想要" int- > char转换,没有什么可以推断出来.

operator+另一方面,对于这种情况,编译器正在查看模板

template<class CharT, class Traits, class Alloc>
    basic_string<CharT,Traits,Alloc>
        operator+( const basic_string<CharT,Traits,Alloc>& lhs,
                   CharT rhs );
Run Code Online (Sandbox Code Playgroud)

并且,试图确定什么时候CharT应该是,它会CharT = char从第一个操作数(如std::stringstd::basic_string<char>),并CharT = int从第二个操作数.这种冲突被标准定义为编译错误.