Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function pointer as template

I just started on C++ so sorry if this is a newbie-ish question. I searched all over the web and didn't find anything about this. In fact I wasn't even sure how to formulate my search...

I saw this code somewhere:

template <class T>
struct SomeStruct
{
    SomeStruct() {}
};

And later, this:

int main()
{
    SomeStruct<void (Foo::*)(int test)> mStruct;
}

The above compiles just fine.

So if I understood it correctly, "void (Foo::*)(int test)" is a function pointer that points to some function in Foo taking a int as argument and returning void.

How can that be a legal argument for the "class T" parameter?

Any help would be appreciated.

like image 971
Wildon Zimmer Avatar asked Dec 10 '22 21:12

Wildon Zimmer


1 Answers

void (Foo::*)(int test) is a type of pointer to member function. A variable of such type can be used to point to member function of class Foo (that returns void and takes a single int argument).

class T is a misnomer there - arbitrary type can be used as a template parameter (the type doesn't have to be declared as class), regardless if the template is declared with template<class T> or template<typename T>.

For this reason I don't use the first form, only the latter.

In context of template parameter list of template declaration, typename and class can be used interchangeably, except you must use class in template template parameters (like template<template<typename, typename> class> before C++1z.

like image 171
milleniumbug Avatar answered Dec 13 '22 11:12

milleniumbug