编译时等效于std :: accumulate() [英] Compile-time equivalent to std::accumulate()

查看:155
本文介绍了编译时等效于std :: accumulate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写编译时版本> std :: accumulate() ,方法是定义一个类模板,该模板将递归地迭代给定范围,并在每次迭代时添加元素。

I tried to code a basic, compile-time version of std::accumulate() by defining a class template that would recursively iterate through a given range and would add the elements at each iteration.

Ubuntu 14.04 上使用 gcc 4.8.4 编译测试程序时,出现以下错误:

When compiling a test program using gcc 4.8.4 on Ubuntu 14.04, I get the following error:

compile-time-accumulate.cpp: In function ‘int main()’:
compile-time-accumulate.cpp:44:40: error: call to non-constexpr function ‘std::vector<_Tp, _Alloc>::const_iterator std::vector<_Tp, _Alloc>::cbegin() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const int*, std::vector<int> >; typename __gnu_cxx::__alloc_traits<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type>::const_pointer = const int*]’
                               v.cbegin(),
                                        ^
compile-time-accumulate.cpp:46:32: error: ‘class __gnu_cxx::__normal_iterator<const int*, std::vector<int> >’ is not a valid type for a template non-type parameter
                               0>::value;

这是代码:

在线运行

#include <iostream>
#include <vector>

template
<
    typename     ResultType,
    typename     IteratorType,
    IteratorType Iterator,
    int          RangeLength,
    ResultType   InitialValue
>
struct accumulator
{
    static_assert(RangeLength > 1, "The range length must be > 1");
    static constexpr ResultType value = InitialValue
                                      + accumulator<ResultType,
                                                    IteratorType,
                                                    Iterator + 1,
                                                    RangeLength - 1,
                                                    *Iterator>::value;
};

template
<
    typename     ResultType,
    typename     IteratorType,
    IteratorType Iterator,
    //int          RangeLength,
    ResultType   InitialValue
>
struct accumulator<ResultType, IteratorType, Iterator, 1, InitialValue>
{
    static constexpr ResultType value = InitialValue + *Iterator;
};


int main()
{
    std::vector<int> v = {4,5,6,7};

    const int a = accumulator<int,
                              decltype(v.cbegin()),
                              v.cbegin(),
                              4,
                              0>::value;

    std::cout << a << std::endl;
}

因此,基本上,该标准不允许在模板参数中使用变量,这就是我在这里所做的事情:

So basically, the standard doesn't allow the use of variables in template arguments, which is what I'm doing here:

const int a = accumulator<int,
                          decltype(v.cbegin()),
                          v.cbegin(),
                          4,
                          0>::value;

问:什么是编码类模板的正确方法(或其他任何编译时计算机制)来实现与 std :: accumulate()

Q: What is the proper method for coding a class template (or any other "compile-time" computation mechanism) for achieving a similar result to std::accumulate() ?

(理想情况下,应该能够传递自定义范围和二进制操作,例如真正的 std :: accumulate()

(Ideally, one should be able pass custom ranges and binary operations like the real std::accumulate())

编辑:代码中使用的 std :: vector 只是一个示例。我也尝试过 std :: array 和C样式的数组,但是我仍然遇到类似的问题。

The std::vector used in the code is just an example. I've also tried std::array and C-style arrays but I still had similar problems.

EDIT2:我不想使用宏。

EDIT3:我不想使用外部库。这里的目标是做一个简单的,独立的编译时计算块。类模板是我的第一个想法,但我愿意接受其他建议/技术。

I don't want to use external libraries. The goal here is to do a simple, self-contained compile-time computation block. Class template was the my first idea, but I'm open to other suggestions/techniques.

推荐答案

std :: vector 的存储在运行时分配。因此,在编译期间不可能遍历std :: vector。

std::vector's storage is allocated during runtime. Thus, is not possible to iterate through a std::vector during compile time.

现在可以使用 std :: array 和原始数组。假设您的 std :: array 变量是 constexpr ,则可以使用以下构造对其进行累加:

Now for std::array and raw arrays. Provided that your std::array variable is a constexpr you could use the following construction to accumulate it:

template<typename T, std::size_t N>
constexpr T compile_time_accumulator(std::array<T, N> const &A, int const i = 0) {
  return (i < N)? A[i] + compile_time_accumulator(A, i + 1) : T(0);
}

实时演示

对于原始数组,还必须声明它们 constexpr ,其结构如下:

And for raw arrays, provided also that they are declared constexpr, the following construction:

template<typename T, std::size_t N>
constexpr T compile_time_accumulator(T const (&A)[N], int const i = 0) {
  return (i < N)? A[i] + compile_time_accumulator(A, i + 1) : T(0);
}

实时演示

现在C ++ 14中有关<$ c的内容$ c> constexpr 更加放松,您可以执行以下操作:

Now in C++14 things about constexpr are more relaxed and you could do the following:

template<typename T, std::size_t N>
constexpr T compile_time_accumulator(T const (&A)[N]) {
  T sum(T(0));

  for(int i = 0; i < N; ++i) {
    sum += A[i];
  }

  return sum;
}

实时演示

template<typename T, std::size_t N>
constexpr T compile_time_accumulator(std::array<T, N> const &A) {
  T sum(T(0));

  for(int i = 0; i < N; ++i) {
    sum += A[i];
  }

  return sum;
}

实时演示

这篇关于编译时等效于std :: accumulate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆