Klaim
Klaim

Reputation: 69752

Uniform Initialization Syntax in complex hierarchy construction?

I'm using GCC 4.4.5.

Here is the reproduction of my problem :

#include <vector>

class Test
{
public:

    Test( int a, int b = 42 ) : m_a( a ), m_b( b ) {}

private:

    int m_a;
    int m_b;    
};

typedef std::vector<Test> TestList;


class TestMaster
{
public:

    TestMaster( TestList tests = TestList() ) : m_tests( tests ) {}


private:

    TestList m_tests;

};

Now, this works :

int main()
{

    TestList test_list = { 15, 22, 38 };


    return 0;
}

But this doesn't compile :

class TestManager : public TestMaster
{
public:

    TestManager()
        : TestMaster( { { 42, 54, 94 } } ) //?
    {}


};



int main()
{

    TestManager test_manager;


    return 0;
}

Or maybe I just don't use the correct syntax? Or is GCC wrong?

The error :

g++ -std=c++0x hello_world.cpp
hello_world.cpp: In constructor \u2018TestManager::TestManager()\u2019:
hello_world.cpp:38: erreur: no matching function for call to \u2018TestMaster::TestMaster(<brace-enclosed initializer list>)\u2019
hello_world.cpp:24: note: candidats sont: TestMaster::TestMaster(TestList)
hello_world.cpp:21: note:                 TestMaster::TestMaster(const TestMaster&)

I also tried a simpler way of doing the same (without inheritance) :

TestMaster test_master = { { 42, 54, 94 } };

With the same errror.

Any idea? I can't see why the semantic wouldn't work here...

Upvotes: 4

Views: 300

Answers (1)

Anthony Williams
Anthony Williams

Reputation: 68631

You've got too many levels of construction going on. Initializer lists only work at one level, so you need to tell it that you want the list to apply to the TestList parameter of TestMaster:

TestMaster test_master(TestList({42,54,94}))

and then the same in the constructor of TestManager:

TestManager()
    : TestMaster( TestList( { 42, 54, 94 } ) )
{}

Upvotes: 4

Related Questions