Is it possible to specify the template parameters when calling the operator ()?

I would like to use the operator() pattern, but not sure if this is possible. Here is a simple test case that will not compile. Is something wrong with my syntax, or is it just not possible?

 struct A { template<typename T> void f() { } template<typename T> void operator()() { } }; int main() { A a; af<int>(); // This compiles. a.operator()<int>(); // This compiles. a<int>(); // This won't compile. return 0; } 
+7
c ++ operator-overloading templates
source share
3 answers

Like the chris mentioned in the comments, no, not a shorthand syntax. You must use the full syntax .operator()<T>() ;

+6
source share

If you really want to use templated operator() and want to avoid writing constructs like a.operator()<int>(); , you can add an auxiliary parameter to it:

 template <typename T> struct type{}; struct A { template<typename T> void operator()(type<T>) { } }; int main() { A a; a(type<int>()); } 

Live demo .


In C ++ 14, you can even omit empty brackets in a(type<int>()); using the variable template:

 template <typename T> struct type_{}; template <typename T> constexpr type_<T> type{}; struct A { template<typename T> void operator()(type_<T>) { } }; int main() { A a; a(type<int>); } 

Live demo .

+4
source share

The exact syntax you want to use is not possible in C ++.

Depending on the real problem that you are trying to solve (which is not in the question), I can present at least three options:

  • Use a named function instead of an operator.
  • Pattern A instead of the operator itself.
  • Use verbose spelling to call operator() (I'm not a big fan of this option).
+2
source share

All Articles