user2614516
user2614516

Reputation: 397

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

class NullClass{
    public:
    template<class T>
        operator T*() const {return 0;}

};

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:

  1. It doesn't have a return type.

  2. What is this operator.

  3. and what it actually does.

Upvotes: 14

Views: 7072

Answers (1)

Quentin
Quentin

Reputation: 63144

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<class T>
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.

Upvotes: 15

Related Questions