C++模板类型的Constexpr成员函数

7

我希望创建一个模板类,其中一个成员是一个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[]?

为什么不用http://coliru.stacked-crooked.com/a/44a76f94302bd9e2? - Marco A.
因为我有一些依赖于该成员的方法。 - barsdeveloper
1个回答

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

然后,“每个问题都可以通过添加或删除一层间接性来解决”。 - Tim Seguine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接