Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define multiple methods with parameters from variadic templates

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?

like image 229
Oliver Zheng Avatar asked Mar 09 '12 20:03

Oliver Zheng


1 Answers

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.

like image 55
Philipp Avatar answered Oct 29 '22 06:10

Philipp