user6482749
user6482749

Reputation: 13

Issue when trying to call a template base class constructor using braced-init-list

New student to c++ so forgive me if I mix up my terminology. Been reading Stroustrup and hes very adamant about using the braced-init-list syntax to to construct and initialize objects which I've been trying to apply in my studies. However I encountered some weird behavior when exploring inheritance with templates and I've been unable to find an answer online so far. Here are a couple of examples:

non template example:

class A {
    int x;
public:
    A(int x = 0) : x{ x } {}; // works as expected.
};

class B : public A {
    int y;
public:
    B(int x = 1, int y = 1) : A(x), y{ y } {}; // old syntax works obviously.
};

template example which fails to compile with the error below:

template<typename T>
class A {
    T x;
public:
    A(T x = 0) : x{ x } {}; // works as expected.
};

template<typename T>
class B : public A<T> {
    T y;
public:
    // Compilation fails on the following line (vs2015).
    // Compiler has an issue with A<T>{ X }. Replacing {} with ()
    // works as expected. Shouldn't it work with {} as well?
    // B(T x = 1, T y = 1) : A<T>( x ), y{ y } {};  
    B(T x = 1, T y = 1) : A<T>{ x }, y{ y } {};  
};

error:

Error   C2059   syntax error: ','
Error   C2334   unexpected token(s) preceding '{'; skipping apparent function body

now what really baffles me is why the following works:

template<typename T>
class C : public A<T> {
    using A_alias = A<T>;
    T z;
public:
    // Why does this workaround work while the expected syntax fails
    // to compile?
    C(T x = 2, T z = 2) : A_alias{ x }, z{ z } {};
};

Can anyone please shed some light on whats going on here, I've been going over the book all the day and I cant find any reference to this and searching has been fruitless so far since I'm not sure exactly what to search for.

Upvotes: 1

Views: 33

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

This looks like a compiler bug. gcc compiles the code in question without a problem, at the --std=c++14 level.

Upvotes: 1

Related Questions