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

查看:166
本文介绍了以编程方式在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天全站免登陆