如何初始化 boost rolling window 累加器?

How to initialize a boost rolling window accumulator?

我想初始化一个 boost rolling window 累加器,而不必在函数调用中进行赋值。

这是我看到每个人都做的:

boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::rolling_mean>> acc(boost::accumulators::tag::rolling_window::window_size = 10);

如何在上面的构造函数调用中没有赋值的情况下创建相同的累加器?

这不是作业,是a named-argument idiom. C++ doesn't have that, really, so this why it looks like an assignment: it's an Expression Template

当然可以找出类型并使用它,但这不会有任何区别,只会让正确使用库变得更加困难:

boost::parameter::aux::tagged_argument_list_of_1<
    boost::parameter::aux::tagged_argument<
        boost::accumulators::tag::rolling_window_size_<0>, const int>>
    init(10);

ba::accumulator_set<double, ba::stats<ba::tag::rolling_mean>> acc(init);

我不了解你,但我更喜欢命名参数表达式。


您显然可以编写一个辅助函数来删除库详细信息:

auto make_accum(int window) {
    return ba::accumulator_set<
        double,
        ba::stats<ba::tag::rolling_mean>> (ba::tag::rolling_window::window_size = window);
}

int main() {
    auto acc = make_accum(10);
}

这只是使用关于集合中统计信息的知识将命名参数变成位置参数。

如果您担心泛型代码,只需将表达式作为泛型情况下的初始值设定项传递即可。这就是库 istelf 的实现方式:

template <typename Stats, typename... Init> auto generic_accum(Init const&... init) {
    return ba::accumulator_set<double, Stats> (init...);
}

演示所有 3 种方法

Live On Coliru

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>

namespace ba = boost::accumulators;

template <typename Stats, typename... Init> auto generic_accum(Init const&... init) {
    return ba::accumulator_set<double, Stats> (init...);
}

auto make_accum(int window) {
    return ba::accumulator_set<
        double,
        ba::stats<ba::tag::rolling_mean>> (ba::tag::rolling_window::window_size = window);
}

int main() {
    {
        boost::parameter::aux::tagged_argument_list_of_1<
            boost::parameter::aux::tagged_argument<
            boost::accumulators::tag::rolling_window_size_<0>, const int>>
            init(10);

        ba::accumulator_set<double, ba::stats<ba::tag::rolling_mean>>
            acc(init);
    }

    {
        auto acc = make_accum(10);
    }

    {
        auto acc = generic_accum<ba::stats<ba::tag::rolling_mean>>(ba::tag::rolling_window::window_size = 10);
    }
}