简体   繁体   中英

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...

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 } ) )
{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM