通过升级,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;
}
我认为使用模板会丢失引用的类型检查?我对吗?
最佳答案
不,类型转换和引用绑定规则相同,无论是否涉及模板。您可以将临时(例如,当裁判员与引用类型不同时需要的临时)绑定到const
引用,但不能绑定到非const
引用。
这就是为什么第二对示例无法编译的原因,也是当参数类型与template参数不匹配时,模板operator=
在较大的示例中无法编译的原因。在这两种情况下,代码都尝试通过类型转换创建一个临时文件并将其绑定到非const
引用。
关于c++ - 模板类中对引用的类型检查是否严格?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8186785/