Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 640
user2614516 Avatar asked Jul 31 '14 13:07

user2614516


People also ask

What is a template parameter?

In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.

What is a template template parameter in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What is a non-type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

How do you declare a template?

To instantiate a template class explicitly, follow the template keyword by a declaration (not definition) for the class, with the class identifier followed by the template arguments. template class Array<char>; template class String<19>; When you explicitly instantiate a class, all of its members are also instantiated.


1 Answers

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.

like image 183
Quentin Avatar answered Sep 20 '22 09:09

Quentin