The problem with {}
is that it has several types it can describe. Now, when you don't specify the type, the compiler need to deduce which input type you ment to send, and it's unable to do that. For this reason you have to specify the type of the {}
.
void test(){
A an_A = A({0.0});
std::list<A> list_of_As;
list_of_As.emplace_back(list<double>{0.0});
}
Another options:
for the next class:
class A {
public:
A(list<double> c, int a){
}
};
You can use:
list_of_As.emplace_back(list<double>{0.0}, 1);
//list_of_As.emplace_back(A({0.0}, 1)); <-- Avoid using this. Explanation is right after this section.
list_of_As.emplace_back(initializer_list<double>{0.0}, 1);
Emplace Vs Push
is there any good reason not to solve the problem with A({0.0}) rather than list{0.0} ?
Yes. emplace_back
used for creating the objects of the list in place instead of copy/move them later to the list. There is no reason for using emplace_back
like it was push_back
. The right way to use emplace_back
is to send it the arguments of the object's constructor, and not the object itself.
push_back
will move your object into the list/vector if only it moved by reference (rvalue) and if the element type has a move assignment operator.
For more reading about move/copy and push_back/emplace_back