加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 可以用重复的函数调用初始化const std :: array吗?

发布时间:2020-12-16 10:07:12 所属栏目:百科 来源:网络整理
导读:参见英文答案 Create N-element constexpr array in C++11????????????????????????????????????7个 是否有可能做到这一点 int foo(){ static int i=0; ret = i++; return ret;}const std::arrayint,3 arr = {{foo(),foo(),foo()}}; 在(模板?)函数中或指定
参见英文答案 > Create N-element constexpr array in C++11????????????????????????????????????7个
是否有可能做到这一点

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,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读