我想实现一类的运算符重载,如:避免在模板类方法隐式转换
template<class T> class A{
public:
T val;
A<T>& operator=(const T& v) {
this->val = v;
return *this;
}
}
所以我可以做:
A<bool> obj;
obj = true; // instead of obj.val = true
obj = false;
这工作得很好。
但是,如果我这样做:
A<bool> obj;
obj = 123123; // bool is not a number!
它仍然有效!我能以某种方式防止这种情况吗
我试图标志着超载explicit
这样的:
explicit A<T>& operator=(const T& v) { ... }
,但我得到一个错误:
error C2071: 'A<T>::operator =': illegal storage class
它甚至有可能做到这一点?
也许这些? http://stackoverflow.com/questions/12877546/how-do-i-avoid-implicit-casting-on-non-constructing-functions-c http://stackoverflow.com/questions/9458741/with-显式删除的成员函数在C11是它仍然值得INN – Salmonstrikes 2015-04-03 03:12:06
@Salmonstrikes否,因为他们只适用于单个函数(而不是_class_方法),它们是特定类型的专业化,不是所有类型 – rev 2015-04-03 03:14:04
鲑鱼的链接的第一个给你想要的 – 2015-04-03 03:18:26