通过促销在C ++中允许以下内容:
int ivalue = true;
bool bvalue = 1;
好吧,好吧。通过类型检查不允许这样做:
int& ivalue = false;
bool& bvalue = 0;
多好。
从维基百科看这个。 http://en.wikipedia.org/wiki/Property_(programming)#C.2B.2B
#include <iostream>
template <typename T> class property {
T value;
public:
T & operator = (const T &i) {
::std::cout << "T1: " << i << ::std::endl;
return value = i;
}
// This template class member function template serves the purpose to make
// typing more strict. Assignment to this is only possible with exact identical
// types.
template <typename T2> T2 operator = (const T2 &i) {
::std::cout << "T2: " << i << ::std::endl;
T2 &guard = value;
return value = i;
throw guard; // Never reached.
}/**/
operator T const & () const {
return value;
}
};
struct Bar {
// Using the property<>-template.
property <bool> alpha;
property <unsigned int> bravo;
};
int main () {
Bar bar;
bar.alpha = true;
bar.bravo = true; // This line will yield a compile time error
// due to the guard template member function.
::std::cout << foo.alpha << ", "
<< foo.bravo << ", "
<< bar.alpha << ", "
<< bar.bravo
<< ::std::endl;
bool bvar = 22;
int ivar = true;
//int &newvar = bvar;
print(bvar);
::std::cout << bvar << " and " << ivar << "\n";
return 0;
}
我认为使用模板对引用的类型检查会丢失吗?我是对的吗?
答案 0 :(得分:1)
不,无论是否涉及模板,类型转换和引用绑定规则都是相同的。您可以将临时(例如,当裁判与参考类型不同时需要的那个)绑定到const
引用,但不能绑定到非const
引用。
这就是为什么第二对示例无法编译的原因,以及当参数类型与模板参数不匹配时,模板operator=
无法在更大的示例中编译的原因。在这两种情况下,代码都会尝试创建临时的直通式转换,并将其绑定到非const
引用。