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;}
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.
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 +.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With