Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method function pointer template without naming class type

Consider this template function, invoking a method of an object of class T.

template<class T, void (T::*Method)()>
void circuitousInvoke(T* callee) {
    (callee->*Method)();
}

Example:

struct A {
    void test() {};
}

circuitousInvoke<A, &A::test>(new A);

As the type T is already known to circuitousInvoke from parameter callee, is there a way to avoid typing this type?

circuitousInvoke<&A::test>(new A);

EDIT

This question refers to template functions only. Inheritance and other class based solutions are not suitable in this case. (In my project using a wrapper object would be more worse than typing an additional name.)

like image 584
PaulProgrammerNoob Avatar asked May 31 '17 18:05

PaulProgrammerNoob


1 Answers

It would be possible in C++17 with auto

template<auto Method, typename T>
void circuitousInvoke(T* callee) {
    (callee->*Method)();
}

and then

A a;
circuitousInvoke<&A::test>(&a);
like image 84
Jarod42 Avatar answered Oct 19 '22 06:10

Jarod42