Domanda

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);
}
È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top