Variadic templates: One method per template argument

Viewed 62

Is there a way to automatically create one method per variadic template argument?

For example, in the code below, I want to be forced to override void x(a &v) and void x(b &v) in class i:

#include <type_traits>
#include <stdlib.h>
#include <stdio.h>

class a {
};

class b {
};

template <typename ...T>
class t {
public:
    virtual void x(T &v) = 0;
};

class i : public t<a, b>
{
};

int
main (int argc, char *argv[])
{
    i ii;
    return 0;
}


2 Answers

You can make a t_impl that holds the virtual function for a single T like

template <typename T>
class t_impl
{
public:
    virtual void x(T &v) = 0;
};

and then t would inherit from it like

template <typename ...T>
class t : t_impl<T>... // can use public, protected or private inheritance
{
public:
    using t_impl<T>::x...; // used to import t_impl<T>::x into the public space
    // any additional common members
};

Instead of making t a variadic template, just template it on a single type:

template <typename T>
class t {
public:
    virtual void x(T &v) = 0;
};

and inherit base classes like this instead:

class i : public t<a>, t<b>
{
    virtual void x(a &v) {}
    virtual void x(b &v) {}
};

Here's a demo.

Related