C ++ template for function call operator

I tried to use the template to overload the function call statement, as in the following program:

#include <stdio.h> struct Apple { template <typename tn> tn value (); template <typename tn> tn operator () (); }; template <> int Apple::value () { return 10; } template <> int Apple::operator () () { return 10; } int main() { Apple apple; printf("Value : %d\n", apple<int>()); printf("Value : %d\n", apple.value<int>()); return 0; } 

While the function call in the second printout does not show any errors, the function call operator in the first print shows the expected primary-expression error. I do not know what I am doing wrong. Can someone help me know the problem in advance.

+6
source share
1 answer

The problem is calling the operator() template (second line of main() ). In your case, you need to explicitly specify the type of the return value, since it cannot be deduced, and the correct way to execute it:

 printf("Value : %d\n", apple.operator()<int>()); 

operator()() is a member function of a template that takes () as parameters. So, its name is operator() , its parameter list () . Therefore, to refer to it, you need to use apple.operator() (its name) and then <int> (template parameter) and then () (parameter list). Replace mentally the name of operator() with FUNCTION , so operator()() is FUNCTION() , and you will see a template. In your case, apple<int>() calls the non-template operator()() on the template instance object apple<int> , i.e. apple<int>.operator()() , which is not what you want.

Is it useful to define such an operator? Probably not, since this leads to an ugly syntax.


You can achieve what you might want using the auto return type in C ++ 14, e.g.

 #include <stdio.h> struct Apple { template <typename tn> tn value (); auto operator () (); }; template <> int Apple::value () { return 10; } auto Apple::operator () () // not a template anymore, return type is deduced int { return 10; } int main() { Apple apple; printf("Value : %d\n", apple()); printf("Value : %d\n", apple.value<int>()); return 0; } 

In this example, auto doesn't really shine, since you can manually specify int as the return type, but in a more complex declaration it can be really useful.

+10
source

Source: https://habr.com/ru/post/983425/


All Articles