如何在编译时创建数组?

时间:2014-09-07 12:40:48

标签: c++ c++11 c++14

template<std::size_t sz>
constexpr std::array<int,sz> range(){
  std::array<int,sz> arr{0};
  std::iota(arr.begin(),arr.end(),0);
  return arr;
}

如果我试着像

那样打电话
auto r = range<10>()

我会收到以下错误

> $ clang++ -stdlib=libc++ -std=c++1y main.cpp -o main && ./main                                                                                  
main.cpp:33:30: error: implicit instantiation of undefined template 'std::__1::array<int, 10>'
constexpr std::array<int,sz> range(){
                             ^
main.cpp:48:12: note: in instantiation of function template specialization 'range<10>' requested here
  auto r = range<10>();
           ^
/usr/include/c++/v1/__tuple:69:65: note: template is declared here
template <class _Tp, size_t _Size> struct _LIBCPP_TYPE_VIS_ONLY array;
                                                                ^
main.cpp:34:22: error: implicit instantiation of undefined template 'std::__1::array<int, 10>'
  std::array<int,sz> arr{0};
                     ^
/usr/include/c++/v1/__tuple:69:65: note: template is declared here
template <class _Tp, size_t _Size> struct _LIBCPP_TYPE_VIS_ONLY array;
                                                                ^
main.cpp:48:12: error: implicit instantiation of undefined template 'std::__1::array<int, 10>'
  auto r = range<10>();
           ^
/usr/include/c++/v1/__tuple:69:65: note: template is declared here
template <class _Tp, size_t _Size> struct _LIBCPP_TYPE_VIS_ONLY array;
                                                                ^
3 errors generated.

我的错误是什么?

1 个答案:

答案 0 :(得分:4)

确保包含

#include <array>
#include <numeric>

http://coliru.stacked-crooked.com/a/fc15a6715178a49b