c++ - C++11 class that can only be implicitly constructed? -
is there way make type has 0 size , can constructed implicitly?
the use case prevent public members of struct being initialized via brace syntax:
class barrier { ... }; struct foo { int user_sets; int* this_to; barrier _bar; int *must_be_zero_init_by_linker; }; foo foo = {1}; // ok foo bar = {1, nullptr}; // ok foo baz = {1, nullptr, {}}; // must error edit: 1 other constraint: foo object must linker initialized can't define constructors or private members.
you define own constructor; prevents class being aggregate. example:
struct foo { foo(int = 0, int * p = nullptr) constexpr : user_sets(a), this_to(p), must_be(nullptr) {} int user_sets; int* this_to; int *must_be; }; foo foo = { 1 }; // ok foo bar = { 1, nullptr }; // ok // foo baz = { 1, nullptr, {} }; // error in fact, recommend making constructor explicit - can't use copy-initialization, can still use list-initialization:
explicit foo(int = 0, int * p = nullptr) constexpr /* ... */ foo foo { 1 }; // ok foo bar { 1, nullptr }; // ok // foo baz { 1, nullptr, {} }; // error
Comments
Post a Comment