What is operator T* (where T is a template parameter ) in C++?

前端 未结 1 998
猫巷女王i
猫巷女王i 2021-02-20 00:23
class NullClass{
    public:
    template
        operator T*() const {return 0;}

};

I was reading Effective C++ and I came across this

1条回答
  •  逝去的感伤
    2021-02-20 00:49

    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.

    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
    explicit operator T*() const {return 0;}
    

    This avoid implicit conversions (which can be a subtle source of bugs), but permits the usage of static_cast.

    0 讨论(0)
提交回复
热议问题