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

How to initialize an array in a class whose values can be used in constant-expressions?

本文关键字:常量 表达式 初始化 数组      更新时间:2023-10-16

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

// 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或元编程?)

非常感谢!

EDIT:正如标题所指定的,我需要array作为类的成员(而不是全局数组)。

是的,您可以将其设为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];

如果您想知道元编程示例会是什么样子,下面是一个示例:

#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;
}