c++ - uniform initialization with variadic templates -
i have pod chparam
, it's parameter in variadic template function set
. i'd pass function arguments(constructor parameters) in curly braces p.set({ param::d, 1000.f }, { param::p, 2000.f })
. , thought constructor called implicitly , chparam
objects created. it's impossible, should explicitly create object a.set(chparam{ param::d, 1000.f }, chparam{ param::p, 2000.f });
is possible somehow use variant p.set({ param::d, 1000.f }, { param::p, 2000.f })
?
#include <iostream> using namespace std; using float = float; enum class param : size_t { d = 0, p }; struct chparam { param tag_; float value_; }; class pipecalcparams { private: float d_, p_; public: pipecalcparams() : d_(0), p_(0) {} pipecalcparams& set_d(float d) { d_ = d; return *this; } pipecalcparams& set_p(float p) { p_ = p; return *this; } template <typename... args> pipecalcparams& set(const chparam& p, args&&... args) { set(p); return set(args...); } pipecalcparams& set(const chparam& p) { switch (p.tag_) { case param::d: set_d(p.value_); break; case param::p: set_p(p.value_); break; } return *this; } }; int main() { pipecalcparams a; a.set(chparam{ param::d, 1000.f }, chparam{ param::p, 2000.f });//ok pipecalcparams p; p.set({ param::d, 1000.f }, { param::p, 2000.f });//error: no matching function call 'pipecalcparams::set(<brace-enclosed initializer list>, <brace-enclosed initializer list>)' p.set({ param::d, 1000.f }, { param::p, 2000.f }); return 0; }
it not directly possible use
{ param::d, 1000.f }
as function parameter when needs deduced. reason braced initializer list has no type. since not have type, type cannot deduced compiler. have along. can did , specify type like
chparam{ param:d, 1000.f }
or can specify type of object expecting. if want variable numbers of same types std::intializer_list
work. allows compiler construct elements individual braced initializer lists. using code like
pipecalcparams& set(std::initializer_list<chparam> args)
and when call use
p.set({{ param::d, 1000.f }, { param::p, 2000.f }})
do note set of curly braces used. outermost set declares std::intializer_list
, each inner set declares each chparam
in list.
Comments
Post a Comment