Hug*_*gus 7 c++ templates class operator-overloading
我有以下代码无法编译,抱怨+ =运算符不存在.+ =运算符在此处声明在A类之外.
template < typename _T >
class A {
public:
operator _T () const { return 42 ; }
};
template <typename _T >
A< _T > & operator += ( A< _T > & l, _T r ) { return l ; }
int main() {
A< int > e, f ;
e += f ;
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我在类A中实现运算符,代码编译并工作:
template < typename _T >
class A {
public:
operator _T () const { return 42 ; }
A< _T > & operator += ( _T r ) { return *this ; }
};
int main() {
A< int > e, f ;
e += f ;
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
这两个代码有什么区别?它们不应该是等价的吗?
这是用gcc 4.4.7-4编译的.
第一个示例无法编译,因为模板参数推断不执行任何转换.同
template <typename _T >
A< _T > & operator += ( A< _T > & l, _T r ) { return l ; }
Run Code Online (Sandbox Code Playgroud)
双方l并r有助于确定哪些_T是.当你这样做时e += f,编译器_T必须得到它int,l并且它r必须是,A<int>因为那是类型f.由于它们不匹配,因此无法编译.
在第二个代码中,没有模板参数推断.编译器知道什么_T是从类的实例,因此所有它需要能够做的是什么转换传递给r到_T.
我还建议你不要习惯用下划线开始名字.有一些关于它们的规则,如果你违反它们,那么你的程序有未定义的行为,因为它们是为实现保留的.有关更多信息,请参阅在C++标识符中使用下划线有哪些规则?