我想使用可变参数模板编写线性叠加的抽象。为此,我想定义一个显示某种形式的 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?
- 一个更好的解决方案当然是编写一个 Superposition 类,它不需要从基类派生 MyField,而是直接解析 MyField 的 operator()。我能以某种方式做到这一点吗?
感谢您的帮助!
最佳答案
首先,直接解决您的问题。
一些元编程样板:
template<class...>struct types{using type=types;};
一个 hana 风格的函数,它提取一个参数的类型,可以选择使用一个模板来根据以下条件进行提取:
template<template<class...>class Z, class...Args>
constexpr types<Args...> extract_args( Z<Args...> const& ) { return {}; }
将以上内容包装在 decltype
中的别名为了便于使用:
template<template<class...>class Z, class T>
using extract_args_from = decltype( extract_args<Z>( std::declval<T>() ) );
Superposition 的主模板留空,默认参数提取 Superposable
的类型参数:
template<class S, class Args=extract_args_from<Superposable, S>>
class Superposition;
然后是获得 Result
的特化和 Parameters
S
的(可能是基类)的类型的 Superposable
:
template<class S, class Result, class...Parameters>
class Superposition< S, types<Result, Parameters...>> {
live example .顺便说一句,你错过了 virtual
.
请注意,我不赞成您的设计——结果应该是返回值(自然),使得 ()
virtual 似乎不是一个好主意(我会改用 CRTP,如果我真的需要隐藏特定的实现,则使用类型删除)。
您可以删除 Superposable
的正文它按原样工作:
public:
typedef Result result_t;
void operator()(Result& result, const Parameters&...) const = 0;
我至少会推荐。
下一步是摆脱继承和推导Parameters
完全:
class MyField {
public:
double operator()(const double& p1, const double& p2) const {
return p1 + p2;
}
};
template<typename S> // where S must be inherited from Superposable
class Superposition {
private:
std::vector< std::shared_ptr<S> > elements;
public:
template<class...Parameters,
class R=std::result_of_t<S&(Parameters const&...)>
>
R operator()(const Parameters&... parameters) const {
R ret = {};
for(auto p : elements){
ret += (*p)(parameters...);
}
return ret;
}
};
它具有完美转发的所有缺陷,但也具有所有优点。
std::result_of_t<?>
是 C++14,但将其替换为 typename std::result_of<?>::type
在 C++11 中作为插件。
关于C++11 可变参数模板 + 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32054116/