为什么不自动向下转换应用于模板功能? [英] Why isn't automatic downcasting applied to template functions?

查看:83
本文介绍了为什么不自动向下转换应用于模板功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Someone asked this question about string appending. It's string s; s = s + 2; not compiling. People gave answers stating that operator+ is defined as a template function while operator+= is not, so auto downcasting (int(2) to char(2)) is not applied.

原型是

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

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

Why can't the compiler just use this prototype and cast int(2) to char(2)?

basic_string<char, _T, _A> operator+(const basic_string<char, _T, _A>, char);

编译器(G ++ 6.3.0)抱怨

The compiler (G++ 6.3.0) complains that

[Note] deduced conflicting types for parameter '_CharT' ('char' and 'int')

推荐答案

关键区别在于,对于operator +=变体,std::basic_string的char类型模板参数,以及其RHS的参数类型为已经固定为char,而operator+模板必须根据其参数推论得出.

The key difference is that for the operator += variant, the char type template argument for the std::basic_string, and thus the argument type for its RHS, is already fixed to char, while the operator+ template has to deduce that from its arguments.

因此,对于+=情况,编译器知道您想要" int-> char转换,没有什么可推论的.

Thus, for the += case, the compiler knows you "want" the int->char conversion, there is nothing to deduce there.

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

For the operator+ case on the other hand, the compiler is looking at the template

template<class CharT, class Traits, class Alloc>
    basic_string<CharT,Traits,Alloc>
        operator+( const basic_string<CharT,Traits,Alloc>& lhs,
                   CharT rhs );

,并且,当尝试确定CharT应该是什么时,它从第一个操作数获取CharT = char(因为std::stringstd::basic_string<char>),而从第二个操作数获取CharT = int.根据标准,这种冲突被定义为编译错误.

and, when trying to determine what CharT is supposed to be, it gets CharT = char from the first operand (as std::string is std::basic_string<char>) and CharT = int from the second operand. Such a conflict is defined to be a compilation error by the standard.

这篇关于为什么不自动向下转换应用于模板功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆