静态反映非POD类的成员函数

时间:2018-01-23 16:06:27

标签: c++ templates reflection variadic-templates c++17

IIUC,现在可以使用例如boost::hanamagic_get轻松地对POD类/结构进行静态反映。

如何对非POD类的某些成员函数执行类似的静态反射? (我正在寻找一种解决方案,它不需要使用实现建议的静态反射扩展的编译器fork。)

在我的特定用例中,我有现有的每个类都有一些setter。我想用适配器包装这些类,该适配器从某些输入生成器中提取适当类型的值,并在适配的实例上调用匹配的setter。

class A {
public:
   void setParam1(double); // To be annotated, e.g. REFLECT_MEM_FUNC(void setParam1(double);)
   void setParam2(Param);  // To be annotated, e.g. REFLECT_MEM_FUNC(void setParam2(Param);)
   void anotherFunc();     // Not annotated

private:
   double param1;
   Param param2;
// ...
};

class B {
public:
   void mySetParam(int);   // To be annotated, e.g. REFLECT_MEM_FUNC(void mySetParam(int);)

private:
   SomeOtherClass inner;   // parameter passed on to this member
// ...
};

template<
   typename AdaptedT, 
   // Tuple of references to classes, each implementing AppropriateParam get();
   // AppropriateParam return type of each getter must match the matching reflected setter.
   // To be clear, it's the instantiator's responsibility to provide matching Inputs; Inputs is not an auto-generated type since it can be anything providing the expected static interface.
   typename Inputs
> class Adapter {
public:
   Adapter(AdaptedT, Inputs);

   // Calls adapted's reflected setters with the values provided by inputs.
   setParametersFromInputs();

private:
   AdaptedT adapted;
   Inputs inputs;
// ... 
};

// Just to demonstrate the static interface expected from an input
template<typename ParamT>
class Input {
public:
   ParamT get();
// ...
};

Input<double> inputDouble { /* ... */ };
Input<Param>  inputParam { /* ... */ };
Adapted<A, std::tuple<Input<double>&, Input<Param>&>> adapter {
   { /* ... */ },
   {inputDouble, inputParam}
};

// Calls:
// adapted.setParam1(std::get<0>(inputs).get());
// adapted.setParam2(std::get<1>(inputs).get());
adapter.setParametersFromInputs();

0 个答案:

没有答案