문제

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);
}
도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top