如何在类中初始化数组,其值可以在常量表达式中使用?

时间:2012-08-04 02:15:22

标签: c++ arrays c++11 initializer-list constexpr

我想知道如何在类中初始化数组,其值可以在常量表达式中使用。 这是我的问题的解释:

// The goal : initializing an array for a class
// whose values can be used as normal static const
// (as template parameters for example)

class MyClass
{
    public:
        static const unsigned int value = 42; // <- No problem here
        static const unsigned int array[3] = {100, 101, 102}; // <- How to initialize this static const array (with constexpr or metaprogrammation maybe ?)
        template<unsigned int T> inline void f() {std::cout<<"Hello, my value is "<<T<<std::endl;} // <- Simple function for demonstration purposes
        inline void fvalue() {f<value>();} // <- No problem here
        inline void farray() {f<array[1]>();} // <- Big problem here
};
//const unsigned int Class1::array[3] = {100, 101, 102}; // <- If I do this, I will initialize the array but farray() will not compile

在C ++ 2011中有没有办法做到这一点? (有constexpr或metaprogrammation可能?)

非常感谢!

编辑:当标题指定它时,我需要array成为类的成员(不是全局数组)。

2 个答案:

答案 0 :(得分:3)

是的,您可以将其设为constexpr ..

使它成为constexpr允许静态成员在类中初始化时具有更多类型,而不仅仅是整数或枚举类型。特别是,成员只需要是文字类型,初始化程序中的所有表达式都必须是常量表达式。所以这很好

class MyClass
{
    public:
        static constexpr unsigned int array[3] = {100, 101, 102};
        template<unsigned int T> inline void f() {
            std::cout<<"Hello, my value is "<<T<<std::endl;
        } // <- Simple function for demonstration purposes
        inline void farray() {f<array[1]>();}
};

// needs a definition out-of-class too. put it into a .cc file
constexpr unsigned int MyClass::array[3];

答案 1 :(得分:0)

万一你想知道元编程示例是什么样的,这是一个例子:

#include <iostream>

template<size_t... values>
struct number_list;

template<size_t value, size_t... values>
struct number_list<value, values...>
{
    static const size_t val = value;
    typedef number_list<values...> next;
};

template<size_t index, typename NumList>
struct indexer
{
    static const size_t val = indexer<index - 1, typename NumList::next>::val;
};

template<typename NumList>
struct indexer<0, NumList>
{
    static const size_t val = NumList::val;
};

template<typename NumList>
class MyClass
{
    public:
        template<size_t T> inline void f() 
        {
            std::cout << "Hello, my value is " << T << std::endl;
        }

        inline void farray() {f<indexer<1, NumList>::val>();}
};

int main()
{
        MyClass<number_list<3, 5, 6>> a;
        a.farray();
        return 0;
}