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?
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.
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).
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.
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++.
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.
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