Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template with an operator

In C++, can you have a templated operator on a class? Like so:

class MyClass { public:     template<class T>     T operator()() { /* return some T */ }; } 

This actually seems to compile just fine, but the confusion comes in how one would use it:

MyClass c; int i = c<int>(); // This doesn't work int i = (int)c(); // Neither does this* 

The fact that it compiles at all suggests to me that it's doable, I'm just at a loss for how to use it! Any suggestions, or is this method of use a non-starter?

like image 891
Toji Avatar asked Jul 12 '09 18:07

Toji


People also ask

How do you write a function operator?

Operator Overloading in Binary Operators Here, + is a binary operator that works on the operands num and 9 . When we overload the binary operator for user-defined types by using the code: obj3 = obj1 + obj2; The operator function is called using the obj1 object and obj2 is passed as an argument to the function.

How do you call a template operator?

operator()() is a template member function that takes () as parameters. So, its name is operator() , its parameter list is () . Therefore, to refer to it, you need to use apple. operator() (its name), followed by <int> (template parameter), then followed by () (parameter list).

How do you declare a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.

What is function template give an example?

Function Templates We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray(). Know more about Generics in C++.


1 Answers

You need to specify T.

int i = c.operator()<int>(); 

Unfortunately, you can't use the function call syntax directly in this case.

Edit: Oh, and you're missing public: at the beginning of the class definition.

like image 67
avakar Avatar answered Oct 05 '22 14:10

avakar