gpt4 book ai didi

模板类型的 C++ Constexpr 成员

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:58 25 4
gpt4 key购买 nike

我想创建一个模板类,其成员是一个 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;
};

关于模板类型的 C++ Constexpr 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26886770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com