我的代码看起来像这样:
template <typename Tag, int v>
struct Const
{
static constexpr int value = v;
};
struct Compound
:
Const<struct T1, 111>,
Const<struct T2, 222>
{
Compound(); // constructor is not constexpr
};
我想知道以 struct T1
或 struct T2
作为参数的编译时构造(例如元函数)可以提取为 constexpr int
111
或 222
分别来自 Compound
。
我想我想要一个看起来像这样的元函数,但不知道如何编写它:
template <class C, typename Tag>
struct GetConst
{
static constexpr int value = /* some magic */
};
GetConst<Compound, struct T1>::value == 111
GetConst<Compound, struct T2>::value == 222
有什么想法吗?
最佳答案
语法略有不同(constexpr 函数而不是静态成员变量),但这里是:
template <typename Tag, int v>
constexpr int getVal(Const<Tag, v>) {
return v;
}
template <class C, typename Tag>
constexpr int GetConst() {
return getVal<Tag>((C*)nullptr);
}
constexpr int value = GetConst<Compound,T2>();
int main() {
std::cout << value << std::endl;
}
关于从模板化基类检索 constexpr 的 C++ 元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37973436/