用Pattern模式初始化`constexpr`数组 [英] Initializing `constexpr` Array with Pattern

查看:308
本文介绍了用Pattern模式初始化`constexpr`数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个使用可变参数模板参数生成的模式初始化一个 constexpr 数组。为了简单起见,考虑使用类型列表的大小初始化 constexpr unsigned 静态数组的问题,例如 unsigned,short,char,int ,long 。我怎么能这样做,所有的计算是在编译时完成的?我需要的解决方案,以使用C ++类型系统,所以我不能使用宏。



我可以想到的最好的方法如下所示,但使用 g ++ -std = c ++ 11 -Wall -Ofast -S (使用g ++ 4.7)和检查程序集清楚地表明,值在运行时被推入堆栈。



如果我能以某种方式告诉扩展,使用数组初始值设置如下: n + 1 关于展开 n



static constexpr unsigned foo [] = {compute_element< Args> :: value ...}; p>

编辑:等等,不介意,我有一个大脑。



这里是代码 answer

  #include< iostream> 

template< class ... Args>
struct foo
{
static constexpr unsigned bar [] = {sizeof(Args)...};
};

int main()
{
std :: cout< foo< unsigned,short,char,int,long> :: bar [2]< std :: endl;
return 0;
}

非常感谢您的时间!

解决方案

这是答案。请记住,由于C ++的限制,我认为这只能在编译的时候创建与可变参数模板参数包大小相同的数组。

  #include< iostream> 

template< class ... Args>
struct foo
{
static constexpr unsigned bar [] = {sizeof(Args)...};
};

int main()
{
std :: cout< foo< unsigned,short,char,int,long> :: bar [2]< std :: endl;
return 0;
}


I would like to initialize a constexpr array with a pattern that is generated using variadic template parameters. For simplicity, consider the problem of initializing a constexpr unsigned static array with the sizes of a list of types, say, unsigned, short, char, int, long. How can I do this so that all of the computation is done during compile time? I need the solution to play nice with the C++ type system, so I cannot use macros.

The best I could come up with is shown below, but compilation using g++ -std=c++11 -Wall -Ofast -S (using g++ 4.7) and inspection of the assembly clearly reveals that the values are pushed onto the stack during runtime. Any ideas? and works fine.

Using an array initializer as follows would work if I could somehow tell the expansion n +1 about expansion n.

static constexpr unsigned foo[] = { compute_element<Args>::value... };

Edit: Wait, never mind, I had a brainfart. The line above works fine...

Here is the code answer:

#include <iostream>

template <class... Args>
struct foo
{
    static constexpr unsigned bar[] = { sizeof(Args)... };
};

int main()
{
    std::cout << foo<unsigned, short, char, int, long>::bar[2] << std::endl;
    return 0;
}

Thank you very much for your time!

解决方案

Here is the answer. Keep in mind that due to limitations in C++, I think that this can only be done in-compile time to create arrays that are of the same size of the variadic template parameter pack.

#include <iostream>

template <class... Args>
struct foo
{
    static constexpr unsigned bar[] = { sizeof(Args)... };
};

int main()
{
    std::cout << foo<unsigned, short, char, int, long>::bar[2] << std::endl;
    return 0;
}

这篇关于用Pattern模式初始化`constexpr`数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆