C++ 模板类型的 Constexpr 成员

C++ Constexpr member of template type

本文关键字:Constexpr 成员 类型 C++      更新时间:2023-10-16

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

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

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