It seems I don't understand braced init lists at all. Why does the following compile for operator=() (entity e
) but not for the constructor (entity f
)?
#include <cstdio>
#include <utility>
#include <string_view>
struct entity
{
using keyval_t = std::pair<std::string_view, std::string_view>;
entity() = default;
entity(keyval_t keyval) {
printf("our special ctor called!\n");
}
auto operator=(keyval_t keyval) {
printf("our special operator called!\n");
}
};
int main()
{
entity e;
// entity f = { "Hello", "World"}; <-- doesn't work??
e = { "Hello", "World" };
}
Bonus question: How do I make it work in both cases?
std::pair
has two member variables, thus two given values should be passes to.This works
entity f = { "Hello", "World"};
implies calling a constructor with 2 parameters, thatentity
does not have. Same asentity f{"Hello", "World"};
orentity f("Hello", "World");
.e = { "Hello", "World" };
is justoperator=(keyval_t)
call with akeyval_t{"Hello", "World"}
, sincekeyval_t
has a constructor with 2 parameters.