1

定数式で値を使用できるクラスの配列を初期化する方法を知りたいです。これが私の問題の説明です:

// 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またはメタプログラミングで多分?)

どうもありがとうございます !

編集:タイトルが指定しているように、私arrayはクラスのメンバーである必要があります(グローバル配列ではありません)。

4

2 に答える 2

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];
于 2012-08-04T03:34:18.137 に答える
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;
}
于 2012-08-04T04:15:10.333 に答える