Define multiple methods with parameters from variadic templates

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-18 12:35:03

问题


I want to define a base template class in a way so that it takes variadic template arguments and defines a virtual method for each argument, where the parameter is the argument type.

E.g. Base<int, bool, string> should give me 3 virtual methods: Foo(int), Foo(bool), and Foo(string).

I tried the following:

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

template <typename... Params>
struct Base : public BaseSingle<Params>...
{
};

Unfortunately, Foo becomes ambiguous. I can't get the using BaseSingle<Params>::Foo... syntax to work. Is there a way?

I know that, alternatively, I can recursively inherit from BaseSingle and pass in the remaining params. Are there perf implications of that?


回答1:


Here is a suggestion that requires exact type matching:

#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"));
}

But IMO your own suggestion using recursive inheritance sounds more elegant.



来源:https://stackoverflow.com/questions/9640256/define-multiple-methods-with-parameters-from-variadic-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!