请考虑以下Boost.Accumulator示例,其中value_type是一个完整的类型:
typedef boost::accumulators::features <
boost::accumulators::tag::sum
, boost::accumulators::tag::min
, boost::accumulators::tag::max
, boost::accumulators::tag::mean
> Features;
typedef boost::accumulators::accumulator_set <
value_type
, Features
> Accumulator;但是,从accumulator_set中提取值对于min、max和sum是有意义的,而且返回类型也很清楚。那么类型for (accu是一个变量)呢:
boost::accumulator::extract_result < tag::mean > ( accu );我想这种类型是double。这种类型是如何推导出来的?
发布于 2014-12-17 12:54:02
这激发了我的兴趣,所以我在boost源代码中完成了它。
我用value_type = int创建了一个累加器。extract_result的结果确实是双倍的。
这是在extract_result<>中由这一行推导出来的:
typename mpl::apply<AccumulatorSet, Feature>::type::result_type 这反过来又取决于这一行:
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;(其中样本为int)
在此部分专门用于在分割时将ints强制为双倍:
// partial specialization that promotes the arguments to double for
// integral division.
template<typename Left, typename Right>
struct fdiv_base<Left, Right, typename enable_if<are_integral<Left, Right> >::type>
: functional::divides<double const, double const>
{};示例程序:
#include <iostream>
#include <typeinfo>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
typedef boost::accumulators::features <
boost::accumulators::tag::sum
, boost::accumulators::tag::min
, boost::accumulators::tag::max
, boost::accumulators::tag::mean
> Features;
typedef boost::accumulators::accumulator_set <
int
, Features
> Accumulator;
using namespace std;
int main()
{
Accumulator acc;
acc(0);
acc(99);
auto mean = boost::accumulators::extract_result < boost::accumulators::tag::mean > (acc);
cout << "mean is " << mean << " of type " << typeid(mean).name() << endl;
}编辑:
检查:
typename mpl::apply<AccumulatorSet, Feature>::type::result_typeAccumulatorSet是我们的累加器(从参数推导到extract_result),Feature是tag::mean tag::mean exports impl,这是一个impl::mean_impl<mpl::_1, sum>
extract_result函数调用find_accumulator<Feature>(acc),它返回对mpl::apply<Feature>::type的引用(以累加器作为参数的函数对象)。
对此对象调用_1 (),其中_1是和(累加器),mean_impl可以从其中提取用于参数类型推断的sample_type到fdiv<>。
不幸的是,模板元功能很难编写,甚至更难阅读!
https://stackoverflow.com/questions/27524034
复制相似问题