C ++ Constexpr模板类型成员

时间:2014-11-12 12:13:57

标签: c++ templates c++11 initialization constexpr

我想创建一个模板类,其成员是constexpr数组。当然,数组需要根据其类型进行不同的初始化,但我不能在不初始化的情况下声明数组。问题是我在模板专业化之前不知道数组的值。

//A.hpp
template<typename T>
class A {
public:
    static constexpr T a[];
    constexpr A() {};
    ~A() {};
}
//B.hpp
class B: public A<int> {
public:
    constexpr B();
    ~B();
};
//B.cpp
template<>
constexpr int A<int>::a[]={1,2,3,4,5};
B::B() {}
B::~B() {}

如何在B?

中正确初始化A :: a []

1 个答案:

答案 0 :(得分:6)

每个问题都可以通过添加另一层间接(除了太多间接)来解决:

// no a[] here.
template <typename T> struct ConstArray;

template <> 
struct ConstArray<int> {
    static constexpr int a[] = {1, 2, 3, 4, 5};

    int operator[](int idx) const { return a[idx]; }
};

template <typename T>
class A {
    static constexpr ConstArray<T> a;
};
相关问题