Bill Li
Bill Li

Reputation: 678

Operator overloading in template in C++

I read following code from somewhere:

template<class T> class A {
    T a;
public:
    A(T x):a(x) {}
    operator T() const {return a;}   // what is point here?
};


int _tmain(int argc, _TCHAR* argv[])
{
    A<int> a = A<int>(5);
    int n = a;
    cout << n;
    return 0;
}

What does below line mean?

operator T() const {return a;}

Upvotes: 8

Views: 219

Answers (3)

It means if you want to convert an instance into a T you can use this operator, which here returns a copy of the private member.

In your example code that is how you can assign a, which is of type A<int> to an int directly. Try removing the operator T() and see how that fails to compile, with an error about assigining A<T> to an int.

With the non explicit constructor (the opposite of marking a constructor explicit) there too it makes this type behave a lot like the template type itself in a number of circumstances. In effect you've wrapped a T inside another class that behaves like a T when it needs to. You could extend this to do other, more useful things like monitoring/logging/restricting the use of real instances by hiding them behind something which controlled them.

Also notice how you can change A<int> a = A<int>(5); to simply A<int> a = 5; because of the implicit constructor.

Upvotes: 3

Praetorian
Praetorian

Reputation: 109289

operator T() const {return a;}

This is the typecast operator. It'll implicitly convert the class instance to T. In the example code you've posted this conversion is being performed at the line

int n = a;

Upvotes: 4

John Humphreys
John Humphreys

Reputation: 39354

It's basically making a functor - which is an object with function semantics. That means you can call the object just like a function as a replacement in places where you may have used a function - its a generic programming concept.

It's beneficial because you can have multiple instances of that function-object (functor) and they can each maintain their own state, where as if you had a straight-up function then it could only maintain state via static variables, and it would thus not be re-entrant (you only ever get one instance of a static variable).

Functors are heavily used in STL algorithms as an extra optional parameter.

Upvotes: -5

Related Questions