什么是C ++中的运算符T *(其中T是模板参数)? [英] What is operator T* (where T is a template parameter ) in C++?
问题描述
class NullClass{
public:
template<class T>
operator T*() const {return 0;}
};
我正在阅读有效的C ++,遇到了这个类,我实现了该类并进行编译.我对此有一些疑问:
I was reading Effective C++ and I came across this class, I implemented the class and it compiles. I have a few doubts over this:
-
它没有返回类型.
It doesn't have a return type.
这是什么运算符.
及其实际功能.
推荐答案
这是类型转换运算符.它定义了类的实例和指定的类型(此处为T*
)之间的隐式转换.它的隐式返回类型当然是相同的.
That's the type conversion operator. It defines an implicit conversion between an instance of the class and the specified type (here T*
). Its implicit return type is of course the same.
这里NullClass
实例,当提示转换为任何指针类型时,将产生从0
到所述类型的隐式转换,即该类型的空指针.
Here a NullClass
instance, when prompted to convert to any pointer type, will yield the implicit conversion from 0
to said type, i.e. the null pointer for that type.
顺便说一句,可以明确指定转换运算符:
On a side note, conversion operators can be made explicit :
template<class T>
explicit operator T*() const {return 0;}
这避免了隐式转换(它可能是错误的细微来源),但允许使用static_cast
.
This avoid implicit conversions (which can be a subtle source of bugs), but permits the usage of static_cast
.
这篇关于什么是C ++中的运算符T *(其中T是模板参数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!