Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template argument deduction for member function pointers

Tags:

c++

templates

It is known that template arguments can be pointers to member functions.

So I can write:

struct Bar
{
    int fun(float x);
};

template <int (Bar::*FUN)(float)>
struct Foo
{ /*...*/ };

typedef Foo<&Bar::fun> FooBar;

But what if I want the the Bar type itself to be a template argument:

template <typename B, int (B::*FUN)(float)>
struct Foo
{ /*...*/ };

typedef Foo<Bar, &Bar::fun> FooBar;

Now, when I use it, I have to write Bar twice!

My question is: Is there a way to force the compiler to deduce the class type automatically?

The objective is for this to just work:

typedef Foo<&Bar::fun> FooBar;
typedef Foo<&Moo::fun> FooMoo;
like image 667
rodrigo Avatar asked Jul 31 '12 17:07

rodrigo


People also ask

What is template argument deduction?

Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.

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 member functions be declared as template?

The term member template refers to both member function templates and nested class templates. Member function templates are function templates that are members of a class or class template. Member functions can be function templates in several contexts.

Can there be more than one argument to template?

Yes, like normal parameters, we can pass more than one data type as arguments to templates.


1 Answers

Simple answer: no there isn't.

The problem is that for typedef Foo<&Bar::fun> FooBar; to work, the template would have to have a single non-type argument, but the type of that argument would be unknown when the template is being declared, which is not valid. On the other side, type deduction is never applied to the arguments of the template (only to the arguments to function templates, but those are the arguments to the function, not the template).

like image 120
David Rodríguez - dribeas Avatar answered Oct 07 '22 05:10

David Rodríguez - dribeas