Magix
Magix

Reputation: 5339

Extract type from variadic template class for member function overloading

I would like to have a function overload for each type of a variadic template class. Is that possible ?

template<typename ...args>
class Example {
    virtual void doSomething(args(0) arg) { ... } 
    virtual void doSomething(args(1) arg) { ... }
    /// etc... implementations are the same, but I need access to the type
}

I tried using fold expressions but I'm pretty sure I'm not on the right track. Because I need the functions to be virtual, I cannot declare them as template<typename T> virtual void doSomething(T arg) because, well, template virtual functions aren't allowed.

Upvotes: 1

Views: 182

Answers (1)

Radoslav Voydanovich
Radoslav Voydanovich

Reputation: 481

You can derive the class from a templated pack of instantiations of a base class template that defines one virtual function with its single template parameter as the function parameter type. The derived class then holds the function overloads for each template argument type, that are all virtual.

template<typename arg>
class Base {
    virtual void doSomething(arg arg) {}
};

template<typename ...args>
class Example : public Base<args>... {};

Upvotes: 1

Related Questions