【问题标题】:Why the accumulators from the C++ boost library have function-like interface?为什么 C++ boost 库中的累加器具有类似函数的接口?
【发布时间】:2019-11-13 15:59:57
【问题描述】:

在 boost 库中,我们使用这样的累加器:

acc(1); // push things into acc
cout << max( acc ) << endl; // get its result

为什么我们不能这样定义它的接口:

acc.push(1);
cout << acc.max() << endl;

那么为什么 boost 库中的累加器有一个类似函数的接口呢?它有什么好处?

【问题讨论】:

    标签: c++ boost interface rationale boost-accumulators


    【解决方案1】:

    这是我的猜测

    之所以使用运算符()而不是push()进行推送,是因为acc(value)读取“累积另一个值”,这听起来比acc.push(value)更自然 "将值推入累加器"

    除了累加器可以接收诸如协变量或权重之类的可选功能,这样可能结果看起来和听起来都比acc.push(value, feature) 更好。来自the documentation的一些例子:

    acc( 1.2, covariate1 =  12 );
    acc( 2.3, covariate1 = -23 );
    acc( 3.4, covariate1 =  34 );
    acc( 4.5, covariate1 = -45 );
    
    acc(1, weight = 2); //   1 * 2
    acc(2, weight = 4); //   2 * 4
    acc(3, weight = 6); // + 3 * 6
    
    acc(1, weight = 2, covariate1 = 3);
    acc(0, weight = 4, covariate1 = 4);
    acc(2, weight = 9, covariate1 = 8);
    

    然后使用max(acc) 代替acc.max(),因为它允许可扩展性,同时仍保持一致性。通过编写一个接收累加器的新函数,您将能够对累加列表执行其他操作

    std::cout << "Mean:   " << mean(acc) << std::endl;
    std::cout << "Moment: " << accumulators::moment<2>(acc) << std::endl;
    

    如果使用了成员方法,那么只有有限数量的默认操作,如acc.mean()acc.max(),其余的必须像函数一样使用,如product(acc)rolling_moment&lt;2&gt;(acc)、@ 987654335@,skewness(acc)...

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      相关资源
      最近更新 更多