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

c – 声明后是否可以在constexpr数组中设置元素的值?

发布时间:2020-12-16 10:37:18 所属栏目:百科 来源:网络整理
导读:是否可以在一个点声明一个const数组(可能是constexpr),然后在另一个地方定义它,一次一个元素? 例如. extern constexpr int myArray[100];myArray[0] = myConstexprFunction(0);myArray[1] = myConstexprFunction(1);// ...myArray[100] = myConstexprFuncti
是否可以在一个点声明一个const数组(可能是constexpr),然后在另一个地方定义它,一次一个元素?

例如.

extern constexpr int myArray[100];


myArray[0] = myConstexprFunction(0);
myArray[1] = myConstexprFunction(1);
// ...
myArray[100] = myConstexprFunction(100);

我想要做的就是需要这样的东西.也许有可能使用像:http://b.atch.se/posts/constexpr-counter/这样的东西

但是,如果这种技术在下一个C标准中是非法的(我希望不是),我想使用更安全的技术.

[编辑]如何放松一些要求..让我们说我想做这样的事情:

constexpr int myConstExprFunction(int arg) { return arg + 100;}
// other code...
constexpr int a = myConstExprFunctionBegin(10);
constexpr int b = myConstExprFunction(20);
constexpr int c = myConstExprFunction(30);
constexpr int d = myConstExprFunctionEnd(40);

我想要的是myConstExprFunctionEnd能够使用前面函数创建的值生成最终数组.
编译时的一切当然.

[EDIT2] C 11解决方案非常受欢迎

解决方法

看看你的编辑,我只回答否,因为编译器无法将一组变量转换为数组.它只是不那样工作. C中没有任何构造可以采用一堆声明,删除它们并用另一个声明替换它.源代码预处理器或生成器可能能够允许您搜索的语法.

如果您对不需要外部工具的解决方案感兴趣,可以创建一个返回数组的constexpr函数:

constexpr auto makeMyArray() {
    std::array<int,100> myArray;

    myArray[0] = myConstExprFunction(10);
    myArray[1] = myConstExprFunction(20);
    // ...

    return myArray;
}

然后,初始化您的数组:

constexpr auto myArray = makeMyArray();

(编辑:李大同)

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

    推荐文章
      热点阅读