Martin Perry Martin Perry - 1 month ago 7
C++ Question

C++ template parameter as function call name

In C++, is possible to make something like this:

class A
{
public:
template <typename ClassType, typename MethodName, typename ...Args>
static func()
{
ClassType t = GetPtr<ClassType>();
t->MethodName(GetArg<Args>()...);
}
}

A::func<B, sum, double, double>(); //should call B->sum(double, double)
A::func<C, sum2, std::string, double, double>(); //should call C->sum2(std::string, double, double)


where
GetPtr
and
GetArgs
are working methods to obtain pointers from dictionary.

Answer

You could make use of non-type template parameters like:

template <typename ClassType, typename MethodType, MethodType MethodName, typename ...Args>
static void func() {
    ClassType t = GetPtr<ClassType>();
    (t->*MethodName)(GetArg<Args>()...);
}

to use it as follows:

A::func<B, double (B::*)(double,double), &B::sum, double, double>();

When your compiler will support c++17 your code could get even shortened:

template <typename ClassType, auto MethodName, typename ...Args>
static void func() {
    ClassType t = GetPtr<ClassType>();
    (t->*MethodName)(GetArg<Args>()...);
}

With usage:

A::func<B, &B::sum, double, double>();