返回类型boost :: accumulator :: tag :: mean

时间:2014-12-17 10:59:38

标签: c++ boost types

请考虑以下value_type为整数类型的Boost.Accumulator示例:

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中提取值对minmaxsum有意义,并且返回类型是明确的。 (accu是变量)的类型如何:

boost::accumulator::extract_result < tag::mean > ( accu );

我猜类型是double。如何推断出类型?

1 个答案:

答案 0 :(得分:3)

我对此感兴趣,所以我在增强源代码中完成了它。

我用value_type = int创建了一个累加器。 extract_result的结果确实是双倍的。

这是在extract_result&lt;&gt;中推断出来的。通过这一行:

typename mpl::apply<AccumulatorSet, Feature>::type::result_type 

反过来依赖于这一行:

typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;

(其中Sample是int)

这部分专门用于在分割时强制插入双精度:

// 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_type

AccumulatorSet是我们的累加器(从extract_result的参数推导出来的) Featuretag::mean tag::mean导出impl <{1}}

impl::mean_impl<mpl::_1, sum>函数调用extract_result,它返回对find_accumulator<Feature>(acc)的引用(一个以累加器作为参数的函数对象)

对此对象调用result()调用mean&#39; s impl(_1)其中_1是sum(accumulator),其中mean_impl可以从中提取sample_type,其中它用于fdiv&lt参数的类型推导;&GT;

不幸的是,模板元函数难以编写,甚至更难阅读!