Unified initialization syntax in building a complex hierarchy?

I am using GCC 4.4.5.

Here is a 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 it works:

 int main() { TestList test_list = { 15, 22, 38 }; return 0; } 

But this does not compile:

 class TestManager : public TestMaster { public: TestManager() : TestMaster( { { 42, 54, 94 } } ) //? {} }; int main() { TestManager test_manager; return 0; } 

Or maybe I'm just not using the correct syntax? Or is GCC wrong?

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 an easier way to do the same (without inheritance):

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

With the same errror.

Any idea? I don’t understand why semantics do not work here ...

+4
source share
1 answer

You have too many levels of construction. Initializer lists work only on one level, so you need to tell that you want the list to be applied to the TestList TestMaster parameter:

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

and then the same in the TestManager constructor:

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

Source: https://habr.com/ru/post/1342122/


All Articles