使用variadic模板中的参数定义多个方法

Oli*_*eng 6 c++ variadic-templates c++11

我想要的方式来定义基类模板,使得它需要可变参数模板参数和定义每个参数,其中所述参数是所述参数类型的虚拟方法.

例如,Base<int, bool, string>应该给我3种虚拟方法:Foo(int),Foo(bool),和Foo(string).

我尝试了以下方法:

template <typename Param>
struct BaseSingle
{
    virtual void Foo(Param) {};
};

template <typename... Params>
struct Base : public BaseSingle<Params>...
{
};
Run Code Online (Sandbox Code Playgroud)

不幸的是,Foo变得含糊不清.我无法使用using BaseSingle<Params>::Foo...语法.有办法吗?

我知道,或者,我可以递归地从BaseSingle继承并传入剩余的参数.是否存在这方面的影响?

Phi*_*ipp 5

这是一个需要精确类型匹配的建议:

#include <utility>
#include <typeinfo>
#include <string>
#include <iostream>
#include <cstdlib>
#include <memory>

#include <cxxabi.h>

using namespace std;

// GCC demangling -- not required for functionality
string demangle(const char* mangled) {
  int status;
  unique_ptr<char[], void (*)(void*)> result(
    abi::__cxa_demangle(mangled, 0, 0, &status), free);
  return result.get() ? string(result.get()) : "ERROR";
}

template<typename Param>
struct BaseSingle {
  virtual void BaseFoo(Param) {
    cout << "Hello from BaseSingle<"
         << demangle(typeid(Param).name())
         << ">::BaseFoo" << endl;
  };
};

template<typename... Params>
struct Base : public BaseSingle<Params>... {
  template<typename T> void Foo(T&& x) {
    this->BaseSingle<T>::BaseFoo(forward<T>(x));
  }
};

int main() {
  Base<string, int, bool> b;
  b.Foo(1);
  b.Foo(true);
  b.Foo(string("ab"));
}
Run Code Online (Sandbox Code Playgroud)

但IMO你自己使用递归继承的建议听起来更优雅.