Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of variadic base classes

The following code doesn't work. Its intent is to pass arguments to variadic base classes. Is this possible, and if so, what's the right way to implement it? (Clang's error message is: an initializer for a delegating constructor must appear alone, which I don't understand.)

template<class... Visitors>
class Visited: public Visitors...
{
    public:
        template<class F>
        Visited(const F& f): F(f)               {}

        template<class F, class... Rest>
        Visited(const F& f, const Rest&... r):
            F(f), Visited(r...)                       {}
};

struct A {};
struct B {};
struct C {};

int main()
{
    A a;
    B b;
    C c;
    Visited<A,B,C> v(a, b, c);
}
like image 781
foxcub Avatar asked Aug 07 '26 15:08

foxcub


1 Answers

This is much easier and it works with (sufficiently recent versions of) GCC and Clang:

template<class... Args>
Visited(const Args&... args) : Visitors(args)... {}

using one argument per base class. If you want perfect forwarding for the arguments, use the slightly less concise:

template<class... Args>
Visited(Args&&... args) : Visitors(std::forward<Args>(args))... {}

In both cases, consider adding explicit for the case that Visitors is only a single class and you want to avoid accidental conversions.

Live example

like image 172
Daniel Frey Avatar answered Aug 10 '26 07:08

Daniel Frey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!