2

I'm trying to understand this Function passed as template argument. Turns out that in some places I've read about templates, you declare them like this:

template <typename MyTypeName>
class ...

Now what does

template <void (*T)(int &)>

mean exactly? This is more like a question about syntax than of what the code does. As I understood, it makes a templated function that takes a function pointer, and this function receives the reference to an integer as argument.

However, I don't think it fits the syntax for templates. Where's the typename keyword? What is the general template syntax?

The closest I found is this: Why must we do template <class/typename> T instead of just template T. Apparently you can define 'constant' template arguments. So I guess the template syntax is this:

template <arguments>

where arguments can be things of the type: typename T, int N, void T(int), and so on. If that's the case, what is the advantage of defining

template <void (*T)(int &)>
void doOperation()
{
  int temp=0;
  T(temp);
  std::cout << "Result is " << temp << std::endl;
}

like this, instead of doing

void doOperation(void (*T)(int &))
{
  int temp=0;
  T(temp);
  std::cout << "Result is " << temp << std::endl;
}

?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150

1 Answers1

1

Is the template syntax in c++ just template <typename T>?

No. There're three types of template parameters,

  • non-type template parameter;
  • type template parameter;
  • template template parameter.

The typename keyword is needed for declaring type template parameter, and template and typename keyword are needed for declaring template template parameter. Given template <void (*T)(int &)>, T is declared as a non-type template parameter (a function pointer).

And about why not just doing void doOperation(void (*T)(int &)), because we have to declare T as a template parameter, otherwise it'll be just a function parameter name.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405