I'm just approaching c++11's initializer_list, but there is still something not clear to me. Take the following struct:
template<typename T>
struct Foo
{
public:
std::vector<std::vector<T>> bar;
};
I can initialize it using initializer_list this way:
Foo<int> {{{5,2,3}, {4,3,1}}};
Compiles fine. But if I refactor bar member field as private, it doesn't compile:
Error 1 error C2440: 'initializing' : cannot convert from 'initializer-list' to 'Foo'
If bar was a simple vector, adding a constructor taking an initializer_list solve the issue:
template<typename T>
struct Foo
{
public:
Foo(std::initializer_list<T> v) : bar(v){}
private:
std::vector<T> bar;
};
Now the questions are 2:
- How to correctly define a class with nested private containers, in order to construct it through initializer list?
- How the visibility interferes with the compiler? With a public field is able to deduce how to construct the object, making it private prevent it?
Aucun commentaire:
Enregistrer un commentaire