Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 template alias for a method callback

Is it possible to use C++11 template aliases for method callbacks?

I have a templated method that takes a method callback as one of its input parameters, e.g.:

class Foo {
  public:
    template <typename OtherClass, typename T>
    void Bar(void (OtherClass::*callback)(T *));
};

I would like to be able to rewrite the Bar() prototype so that it uses a type since I will be using the same type in several places in the implementation. I tried using the new C++11 alias below but it did not work.

class Foo {
  public:
     // This does not work
     template <typename OtherClass, typename T>
     using Callback = void (OtherClass::*)(T *object);

     void Bar(Callback callback);
};

What am I missing? I could not find an example of how this would work on several of my favorite C++11 reference web sites.

like image 706
user2180977 Avatar asked Jul 04 '26 23:07

user2180977


1 Answers

It does not work that way. This:

template <typename OtherClass, typename T>
using Callback = void (OtherClass::*)(T *object);

Is declaring an alias template, which means you have to instantiate Callback in order to get a type. For instance:

Callback<C, int>

Will resolve into:

void (C::*)(int*)

So your member should be declared this way:

template<typename OC, typename T>
void Bar(Callback<OC, T> callback); 
like image 113
Andy Prowl Avatar answered Jul 07 '26 12:07

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!