我有一个 POD ChParam
,它是可变参数模板函数中的一个参数set
。我想在花括号中传递给函数参数(构造函数参数)p.set({ Param::D, 1000.f }, { Param::p, 2000.f })
。并认为将隐式调用构造函数并ChParam
创建对象。但这是不可能的,我应该明确地创建一个对象a.set(ChParam{ Param::D, 1000.f }, ChParam{ Param::p, 2000.f });
是否有可能以某种方式使用该变体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 for call to 'PipeCalcParams::set(<brace-enclosed initializer list>, <brace-enclosed initializer list>)' p.set({ Param::D, 1000.f }, { Param::p, 2000.f });
return 0;
}