Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variadic template with recursive inheritance and using declaration

I want to do something similar to the code below, except that I don't want to implement func() twice because it will be the same implementation. Do you have any proposal how to accomplish this?

template <typename First, typename... Rest>
class Base : public Base<Rest...> {
public:
    using Base<Rest...>::func;
    void func(First object) {
        // implementation
    }
};

template <typename First>
class Base<First> {
public:
    void func(First object) {
        // implementation
    }
};

struct X {};
struct Y {};
struct Z {};

class Derived : public Base<X, Y, Z> {};

// ...

Derived d;
d.func(X{});
d.func(Y{});
d.func(Z{});
like image 223
airis Avatar asked Dec 23 '22 12:12

airis


2 Answers

With multiple inheritance and an additional using directive:

template <typename First, typename... Rest>
struct Base : Base<First>,  Base<Rest...> {
    using Base<First>::func;
    using Base<Rest...>::func;
};

template <typename First>
struct Base<First> {
    void func(First object) {/*...*/}
};

Live Demo (C++11)

like image 149
AndyG Avatar answered Mar 08 '23 04:03

AndyG


Could be this a solution? (Move definition of func to a common base?)

template <class First>
class Func_impl
{
public:
     void func(First obj) {
     // implementation
     }
}

template <typename First, typename... Rest>
class Base : public Base<Rest...>, Func_impl<First> {
public:
    // no need to declare func here
};


template <typename First>
class Base<First> : public Func_impl<First> {
public:
   // no need to declare func here
};
like image 29
marom Avatar answered Mar 08 '23 06:03

marom