1

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

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

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

如果在上面的构造函数调用中没有赋值,我怎么能制作相同的累加器?

4

1 回答 1

1

这不是作业,而是命名参数成语。C++ 没有,真的,所以这就是为什么它看起来像一个赋值:它是一个表达式模板

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

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 种方法

住在科利鲁

#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);
    }
}
于 2020-06-26T00:41:33.830 回答