这样可以吗
int foo(){
static int i=0;
ret = i++;
return ret;
}
const std::array<int,3> arr = {{foo(),foo(),foo()}};
在(模板?)函数或指定“为每个成员的初始化调用 foo”的方式中?即
const std::array<int,3> arr = fill_with_foo<3,foo>();
对于上下文,arr 是队列中的缓冲区,将从中读取 N 个元素(在编译时已知)。目前我正在使用代码生成来创建长格式,我有一个函数,它只是分配一个普通数组,用一个 for 循环填充它并返回数组,但我想知道是否可以有缓冲区数组 const。
//编辑:与链接的“重复”不同,我需要
int foo();
在编译时是不确定的,即我认为 constexpr 是不可能的(正如我所说,它需要从运行时填充的队列中读取)。我主要对删除无用的拷贝感兴趣
自 C++ 14 以来,人们可能会使用 std::index_sequnce (或为旧版本手动实现):
namespace detail
{
template<typename T, std::size_t N, typename F, std::size_t... I>
constexpr std::array<T, N> construct(F&& func, std::index_sequence<I...>)
{
return { { (static_cast<void>(I), func())... } };
}
template<typename T, std::size_t N, typename F>
constexpr std::array<T, N> construct(F&& func)
{
return construct<T, N>(std::forward<F>(func), std::make_index_sequence<N>());
}
}
然后您可以按如下方式应用它:
const auto array = detail::construct<T, 3>(foo);
FULL CODE
另请注意,即使在编译时,constexpr
也可以构造 std::array
。
EXAMPLE