我编写一个C++模板类,形式类似如下例子:
template<typename _T, typename _A = SomeClass>
class MyClass
{
public:
typedef MyClass<_T, _A> _MyType;
_MyType &operator=(const _MyType &mytype)
{
......
}
template<typename _Other, typename _AA>
_MyType &operator=(const MyClass<_Other, _AA> &other)
{
......
}
};
第一个等号重载是相同类类型赋值,这个很普通。后面一个赋值重载,我想让不同模板实参实例化的模板类互相赋值,这么写也是可以的。
但是,现在我想加一个限制,就是第二个模板形参必须一样的模板类才能互相赋值!
但是我采用了几种办法都不行,比如:
template<typename _Other>
_MyType &operator=(const MyClass<_Other, _A> &other)
{
这样做在使用时会出现编译错误
}
template<typename _Other, typename _AA>
_MyType &operator=(const MyClass<_Other, _A> &other)
{
这样做也不行
}
幸好,_A一定是个类类型,于是我用了下面这种办法暂时解决了问题,但是,如果_A可以不是类类型怎么办呢?
template<typename _Other, typename _AA>
_MyType &operator=(const MyClass<_Other, _AA> &other)
{
_AA a;
_A b = a;
.....
这样,当_AA和_A类型不同时,就会出编译错误提示你。当然,_AA和_A之间规定不能定义类型转换。
}
LHL