Home > Back-end >  Split variadic template params up to use as single template parameters for other classes
Split variadic template params up to use as single template parameters for other classes

Time:03-17

I'm trying to figure out how to give arbitrary template parameters to a class, then have that class use each of those parameters to instantiate a bass class. Something along these lines:

template<class T>
SingleParamClass;

template<class ... TYPE_LIST>
MultiParamClass : SingleParamClass<TYPE_LIST[0]>, SingleParamClass<TYPE_LIST[1]>... SingleParamClass<TYPE_LIST[N]>;

I've written it with indexing into the parameter pack just for demonstration purposes obviously.

I know how to unpack the type list, but not how to unpack it in a way that I can use it as above.

Edit:

As requested I'll expand on what I'm trying to do...

I want to make a subclass that constructs a series of pure virtual methods using the types in the variadic template params. These pure virtual methods are there for another component to call, and simultaneously forces the dev to implement those methods in the derived class.

In a world where C magically works the way I want, I'd do something like this:

template<class ... TYPE_LIST>
MultiParamClass {

    virtual void func(TYPE_LIST[0] arg) = 0;
    virtual void func(TYPE_LIST[1] arg) = 0;
    ...
    virtual void func(TYPE_LIST[N] arg) = 0;

}

I don't know a way to do this, so I'm trying to find a way around it using subclasses, something like this:

template<class T>
SingleParamClass {
    virtual void func(T arg) = 0;
}

template<class ... TYPE_LIST>
MultiParamClass : SingleParamClass<TYPE_LIST[0]>, SingleParamClass<TYPE_LIST[1]>... SingleParamClass<TYPE_LIST[N]>;

CodePudding user response:

You can expand the parameter pack like so:

template<class T>
struct SingleParamClass {};

template<class ... TYPE_LIST>
struct MultiParamClass : SingleParamClass<TYPE_LIST>... {};

CodePudding user response:

Perhaps try something like this:

template<class T>
class SingleParamClass
{
public:
    virtual void func(T arg) = 0;
};

template<class... TYPE_LIST>
class MultiParamClass : public SingleParamClass<TYPE_LIST>...
{
};

class MyMultiParamClass : public MultiParamClass<int, double, string>
{
public:
    void func(int arg) override { ... }
    void func(double arg) override { ... }
    void func(string arg) override { ... }
};

Online Demo

  • Related