Define multiple methods with parameters from variadic templates

前端 未结 1 416
我在风中等你
我在风中等你 2020-12-29 15:20

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 argum

相关标签:
1条回答
  • 2020-12-29 16:24

    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.

    0 讨论(0)
提交回复
热议问题