Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to use a template operator() but am not sure if it's possible. Here is a simple test case that won't compile. Is there something wrong with my syntax, or is this simply not possible?

struct A {
  template<typename T> void f() { }
  template<typename T> void operator()() { }
};

int main() {
  A a;
  a.f<int>();           // This compiles.
  a.operator()<int>();  // This compiles.
  a<int>();             // This won't compile.
  return 0;
}
like image 854
Paul Avatar asked Aug 20 '14 16:08

Paul


People also ask

Can we pass Nontype parameters to templates?

Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.

Can template have default parameters?

Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.

Can a template be a template parameter?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

What is a template template parameter in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.


2 Answers

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

like image 131
Etienne Maheu Avatar answered Sep 29 '22 07:09

Etienne Maheu


If you really want to use templated operator() and want to avoid writing constructions 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>()); via a 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.

like image 23
Constructor Avatar answered Sep 29 '22 09:09

Constructor