c++ - Is there a succinct way to derive a member's type during construction? -
i have:
- a template routine
unarchivetakes dictionary , key , based on template type (t) passed can specialized producet - a constructor
structleveragesunarchiveconstruct members
an example might following:
template <typename t> t unarchive(const dictionary_t&, key_type key); struct foo { foo(const dictionary& archive) : value_m(unarchive<decltype(value_m)>(archive, value_key)) { } some_value_type value_m; }; the advantage of using unarchive<decltype(value_m)> here can change type of value_m without having update line of code - type follows member variable's type.
the problem have more aesthetic: verbose. have macro:
#define unarchive_for(var) unarchive<decltype(var)> and foo's constructor changes follows:
foo(const dictionary& archive) : value_m(unarchive_for(value_m)(archive, value_key)) { } now have result more terse far uglier. can same result achieved without macro? akin to:
foo(const dictionary& archive) : value_m(unarchive<value_m>(archive, value_key)) { } how can done?
the advantage of using unarchive here can change type of value_m without having update line of code - type follows member variable's type.
one alternative create alias type of value_m , eliminate decltype(value_m) constructor initializer list:
struct foo { using value_type = int; foo(const dictionary_t& archive, const key_type value_key) : value_m(unarchive<value_type>(archive, value_key)) { } value_type value_m; }; the unarchive<value_type> still follows type of value_m. static_assert added ensure type of value_m same value_type if there concern of change type of value_m not changing value_type:
static_assert(std::is_same<decltype(value_m), value_type>::value, "'value_m' type differs 'value_type'"); or set alias based on type of value_m:
int value_m; using value_type = decltype(value_m); if still consider constructor initialization list verbose provide static wrapper function invokes unarchive() function:
struct foo { using value_type = int; foo(const dictionary_t& archive, const key_type value_key) : value_m(unarchive_(archive, value_key)) { } static value_type unarchive_(const dictionary_t& d, key_type k) { return unarchive<value_type>(d, k); } value_type value_m; }; having said that:
value_m(unarchive<decltype(value_m)>(archive, value_key)) is not verbose , precisely states intention.
Comments
Post a Comment