Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specify function interface in template

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}

Compiler Explorer

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading