C++ 模板类型的 Constexpr 成员
C++ Constexpr member of template type
我想创建一个模板类,其中包含一个成员,该成员是一个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;
};
相关文章:
- 添加静态constexpr成员是否会更改结构/类的内存映射
- 初始化模板化类中的静态 constexpr 成员
- 静态 constexpr 成员变量初始化
- 使用静态 constexpr 成员的未解析外部符号
- 使用模板参数还包括 constexpr 成员函数enable_if单独定义和声明模板成员函数
- Constexpr成员函数
- 在模板定义中调用非静态constexpr成员函数
- 在构造函数中使用 constexpr 成员
- emplace_back会导致静态 constexpr 成员上出现链接错误
- l值引用对象上的Constexpr成员函数:Clang和gcc不同意
- 通过呼叫constexpr函数来定义静态constexpr成员
- constexpr:constexpr成员的定义和声明
- 在定义(.cpp文件)中初始化静态浮点 constexpr 成员是可能的
- Clang声称通用lambda参数的constexpr成员不是constexpr
- C 私有静态constexpr成员变量
- constexpr 成员函数,C++中的 std::向量数据成员
- 跨编译器的 constexpr 成员函数的重载解析不一致
- 对静态 constexpr 成员的未定义引用仅由值使用
- 将模板结构用作模板参数与静态constexpr成员
- 从成员变量访问静态 constexpr 成员,GCC 错误?