Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;}

like image 906
Bill Li Avatar asked Aug 23 '11 15:08

Bill Li


People also ask

Is overloading is possible for template functions?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

What is operator overloading with example in C?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

What is a template in C programming?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

What is the syntax of template class?

1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.


2 Answers

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;

like image 174
Praetorian Avatar answered Oct 13 '22 20:10

Praetorian


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.

like image 44
Flexo Avatar answered Oct 13 '22 19:10

Flexo