要在编译时初始化算术类型std::array
的AT
,我这样做了:
#include <array>
#include <iostream>
template<typename AT, auto DIM, auto N = 0>
constexpr void assign(std::array<AT, DIM>& arr, AT value)
{
arr[N] = value;
if constexpr (N < std::size(arr) - 1)
assign<AT, DIM, N + 1>(arr, value);
}
template<typename AT, auto DIM>
constexpr std::array<AT, DIM> zero_array()
{
std::array<AT, DIM> result;
assign(result, AT{0});
return result;
}
template<typename Container>
void print(Container&& cont)
{
for (const auto& el : cont)
std::cout << el << " ";
std::cout << std::endl;
}
int main()
{
auto zero10 = zero_array<double, 10>();
print(zero10);
}
我godbolted it,在我看来它工作:
但是,当我用它编译它时
g++ -O3 -std=c++2a -Wall -Wpedantic -Wunused-parameter -I /usr/include main.cpp -o main
使用g++ (GCC) 8.2.1 20181127
,我得到一个“注意”
In file included from main.cpp:1:
main.cpp: In instantiation of ‘constexpr std::array<AT, DIM> zero_array() [with AT = double; auto DIM = 10]’:
main.cpp:30:42: required from here
/usr/include/c++/8.2.1/array:94:12: note: ‘struct std::array<double, 10>’ has no user-provided default constructor
struct array
^~~~~
/usr/include/c++/8.2.1/array:110:56: note: and the implicitly-defined constructor does not initialize ‘double std::array<double, 10>::_M_elems [10]’
typename _AT_Type::_Type _M_elems;
为什么会有这个说明?我可以忽略它吗?如果是这样,如何摆脱它?
std::array
没有默认构造函数。你需要使用:
std::array<AT, DIM> result = {};
对我来说令人费解的是你为什么认为自己需要zero_array
。如果你使用
std::array<double, 10> a = {};
你得到一个零初始化的对象。