在 C++ 编译时以编程方式创建静态数组 [英] Programmatically create static arrays at compile time in C++

查看:26
本文介绍了在 C++ 编译时以编程方式创建静态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在编译时定义一个静态数组如下:

One can define a static array at compile time as follows:

const std::size_t size = 5;    
unsigned int list[size] = { 1, 2, 3, 4, 5 };

问题 1 - 是否可以使用各种元编程技术在编译时以编程方式"分配这些值?

Question 1 - Is it possible by using various kinds of metaprogramming techniques to assign these values "programmatically" at compile time?

问题 2 - 假设数组中的所有值都相同,是否可以在编译时以编程方式有选择地分配值?

Question 2 - Assuming all the values in the array are to be the same barr a few, is it possible to selectively assign values at compile time in a programmatic manner?

例如:

const std::size_t size = 7;        
unsigned int list[size] = { 0, 0, 2, 3, 0, 0, 0 };

  1. 欢迎使用 C++0x 的解决方案
  2. 数组可能很大,很少百元素长
  3. 现在的数组将只包含POD 类型
  4. 也可以假设大小数组将被事先知道,在静态编译时兼容方式.
  5. 解决方案必须使用 C++ (没有脚本,没有宏,没有 pp或基于代码生成器的解决方案请)

更新:Georg Fritzsche 的解决方案很棒,需要做一些工作才能在 msvc 和 intel 编译器上编译,但仍然是解决问题的非常有趣的方法.

UPDATE: Georg Fritzsche's solution is amazing, needs a little work to get it compiling on msvc and intel compilers, but nonetheless a very interesting approach to the problem.

推荐答案

最接近的是使用 C++0x 功能从可变参数模板参数列表初始化模板的本地或成员数组.
这当然受到最大模板实例化深度的限制,并且必须衡量是否确实对您的情况产生显着影响.

The closest you can get is using C++0x features to initialize local or member arrays of templates from a variadic template argument list.
This is of course limited by the maximum template instantiation depth and wether that actually makes a notable difference in your case would have to be measured.

示例:

template<unsigned... args> struct ArrayHolder {
    static const unsigned data[sizeof...(args)];
};

template<unsigned... args> 
const unsigned ArrayHolder<args...>::data[sizeof...(args)] = { args... };

template<size_t N, template<size_t> class F, unsigned... args> 
struct generate_array_impl {
    typedef typename generate_array_impl<N-1, F, F<N>::value, args...>::result result;
};

template<template<size_t> class F, unsigned... args> 
struct generate_array_impl<0, F, args...> {
    typedef ArrayHolder<F<0>::value, args...> result;
};

template<size_t N, template<size_t> class F> 
struct generate_array {
    typedef typename generate_array_impl<N-1, F>::result result;
};

1..5 案例的用法:

template<size_t index> struct MetaFunc { 
    enum { value = index + 1 }; 
};

void test() {
    const size_t count = 5;
    typedef generate_array<count, MetaFunc>::result A;

    for (size_t i=0; i<count; ++i) 
        std::cout << A::data[i] << "\n";
}

这篇关于在 C++ 编译时以编程方式创建静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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