Allan
Allan

Reputation: 4720

(Simple) constructors in variadic template classes

How would a constructor and a copy constructor look for this variadic template class?

struct A {};
struct B {};

template < typename Head,
           typename... Tail>
struct X : public Head,
           public Tail...
{
    X(int _i) : i(_i) { }

    // add copy constructor

    int i;
};

template < typename Head >
struct X<Head> { };

int main(int argc, const char *argv[])
{
    X<A, B> x(5);
    X<A, B> y(x);

    // This must not be leagal!
    // X<B, A> z(x);

    return 0;
}

Upvotes: 1

Views: 655

Answers (1)

kennytm
kennytm

Reputation: 523724

template < typename Head,
           typename... Tail>
struct X : public Head,
           public Tail...
{
    X(int _i) : i(_i) { }

    // add copy constructor
    X(const X& other) : i(other.i) {}

    int i;
};

Inside the template class, X as a type means X<Head, Tail...>, and all X with different template parameters are distinct types, so the copy constructor of X<A,B> won't match X<B,A>.

Demo: http://ideone.com/V6g35

Upvotes: 1

Related Questions