【发布时间】:2015-11-10 07:26:39
【问题描述】:
我想使用可变参数模板编写线性叠加的抽象。为此,我想定义一个基本类型,它表现出某种形式的 operator() 像这样
template <typename Result, typename... Parameters>
class Superposable {
public:
typedef Result result_t;
void operator()(Result& result, const Parameters&...) const = 0;
};
然后为当前问题从它继承,例如像这样
class MyField : public Superposable<double, double, double> {
public:
void operator()(double& result, const double& p1, const double& p2) const {
result = p1 + p2;
}
};
然后我想写一个抽象基类,可以形成线性叠加,并将Superposable派生类作为模板参数来确定operator()的调用签名。我想要类似的东西
template<typename S> // where S must be inherited from Superposable
class Superposition {
private:
std::vector< std::shared_ptr<S> > elements;
public:
// This is the problem. How do I do this?
void operator()(S::result_t& result, const S::Parameters&... parameters) const {
for(auto p : elements){
S::result_t r;
p->operator()(r, parameters);
result += r;
}
}
};
这是我的问题:
- 如何从 Superposable 派生类中读取类型信息以在 Superposition 中定义我的 operator()?
- 另外,是否有推荐的方法来强制只能使用 Superposable 派生类作为参数调用 Superposition?
- 更好的解决方案当然是编写一个不需要 MyField 从基类派生的 Superposition 类,而是直接解析 MyField 的 operator()。我能以某种方式做到这一点吗?
感谢您的帮助!
【问题讨论】:
标签: c++ templates c++11 inheritance variadic-templates