I have a template class that forwards a function:
template <class T>
class Foo{
template <typename Func, typename... Args>
void Bar(Func function, Args&&... args) {
T t;
(t->*function)(std::forward<Args>(args)...);
}
}
This works, but is there any way to check whether Func is contained in the interface of T, so T::Func? Now, if I enter a wrong function the compiler would complain that t->*function doesn’t exist, but I would like to specify in the function interface that it should be a T::Func. However I can’t seem to get the syntax for this right.
>Solution :
It’s not really necessary to specify this in the signature, since it will fail to compile for the wrong cases anyway, but you could specify member function pointers like this:
template <class T>
class Foo{
public:
template <typename Func, typename... Args>
void Bar(Func T::*function, Args&&... args) {
T t;
(t.*function)(std::forward<Args>(args)...);
}
};
And to call it:
struct S
{
void func(int) {}
};
void freeFunc(int) {}
int main()
{
Foo<S> f;
f.Bar(&S::func, 42); //OK
//f.Bar(&freeFunc, 42); //ERROR
}