2

是否可以将 C++11 模板别名用于方法回调?

我有一个模板化方法,它将方法回调作为其输入参数之一,例如:

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

我希望能够重写 Bar() 原型,以便它使用一种类型,因为我将在实现中的多个地方使用相同的类型。我尝试使用下面的新 C++11 别名,但它不起作用。

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

     void Bar(Callback callback);
};

我错过了什么?在我最喜欢的几个 C++11 参考网站上,我找不到一个例子来说明它是如何工作的。

4

3 回答 3

6

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); 
于 2013-06-15T19:53:18.273 回答
2

You need to include the template parameters:

template <typename U, typename T>
void Bar(Callback<U, T> callback);
于 2013-06-15T19:53:14.277 回答
2

I figured it out. The Bar() method needs to be templated as well.

This works:

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

     template <typename OtherClass, typename T>
     void Bar(Callback<OtherClass, T> callback);
};
于 2013-06-15T19:53:52.003 回答