Let's say I have the following code:
#include <vector>
struct Foo
{
int tag = 0;
std::function<void ()> code;
};
int main()
{
std::vector<Foo> v;
}
And now I want to add a new Foo
item to the vector with the specific tag
and code
without explicitly creating a temporary. That means I must add a constructor for Foo
:
struct Foo
{
inline Foo(int t, std::function<void ()> c): tag(t), code(c) {}
int tag = 0;
std::function<void ()> code;
};
And now I can use emplace_back
:
v.emplace_back(0, [](){});
But when I had to do this again - for the 100th time - with a newly created struct, I thought: can't I use the brace initializer? Like so:
#include <vector>
struct Foo
{
int tag = 0;
std::function<void ()> code;
};
int main()
{
std::vector<Foo> v;
v.push_back(Foo{ 0, [](){} });
}
That gives me a compilation error (cannot convert from 'initializer-list' to 'Foo'), but I hope this can be done and I've just got the syntax wrong.
Foo
is an aggregate and can be initialized using aggregate initialization. – Pilsudski