首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回boost类型::累加器::tag::均

返回boost类型::累加器::tag::均
EN

Stack Overflow用户
提问于 2014-12-17 10:59:38
回答 1查看 566关注 0票数 2

请考虑以下Boost.Accumulator示例,其中value_type是一个完整的类型:

代码语言:javascript
复制
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是有意义的,而且返回类型也很清楚。那么类型for (accu是一个变量)呢:

代码语言:javascript
复制
boost::accumulator::extract_result < tag::mean > ( accu );

我想这种类型是double。这种类型是如何推导出来的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-17 12:54:02

这激发了我的兴趣,所以我在boost源代码中完成了它。

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

这是在extract_result<>中由这一行推导出来的:

代码语言:javascript
复制
typename mpl::apply<AccumulatorSet, Feature>::type::result_type 

这反过来又取决于这一行:

代码语言:javascript
复制
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;

(其中样本为int)

在此部分专门用于在分割时将ints强制为双倍:

代码语言:javascript
复制
// 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>
{};

示例程序:

代码语言:javascript
复制
#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;

}

编辑:

检查:

代码语言:javascript
复制
typename mpl::apply<AccumulatorSet, Feature>::type::result_type

AccumulatorSet是我们的累加器(从参数推导到extract_result),Featuretag::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<>。

不幸的是,模板元功能很难编写,甚至更难阅读!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27524034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档