使用类似机制的模板使用相同的签名调用不同的方法

man*_*ans 4 c++ methods templates c++11

我有这个代码:

struct C
{
   int d1;
   int d2;
};

struct A
{
      void  write(C data)
      {
      }
};

struct B
{
      void use(C data)
      {
      }
};
Run Code Online (Sandbox Code Playgroud)

现在我想定义一个使用AB调用它们writeuse方法的新类.像这样的东西:

template <class T>
struct D
{
     T t;
     D(T myT) { t=myT; }
     void myFunct(C data)
     {
         // t.????(data);
     }
};
Run Code Online (Sandbox Code Playgroud)

正如你可以看到这两个类是否有类似的方法名称,那么它很容易实现D,但由于A并且B有不同的方法,那么我需要告诉编译器它应该使用哪种方法.我怎样才能做到这一点?

我不想改变A或者B我也不想创建一个子类,AB创建一个具有相同名称的方法.

我想要一种方法告诉编译器使用哪种方法作为模板的一部分,是否可能?

Hol*_*olt 10

您可以将指向member-function指针作为第二个模板参数传递给D:

template <class T, void (T::*fun)(C)>
struct D
{
    T t;

    void myFunct(C data)
    {
        (t.*fun)(data);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建D对象:

D<A, &A::write> da;
D<B, &B::use> db;
Run Code Online (Sandbox Code Playgroud)


Rei*_*ica 9

您可以使用自己的特质类轻松完成此操作:

template <class T>
struct DTraits;

template <>
struct DTraits<A> {
  static void call(A &obj, C data) { obj.write(data); }
};

template <>
struct DTraits<B> {
  static void call(B &obj, C data) { obj.use(data); }
};

template <class T>
struct D
{
  void myFunct(C data)
  {
    DTraits<T>::call(t, data);
  }
};
Run Code Online (Sandbox Code Playgroud)