C++ 元函数从模板化基础中检索 constexpr 类

C++ metafunction to retrieve constexpr from templated base classes

我的代码看起来像这样:

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 T1struct T2 作为参数的编译时构造(例如元函数)可以提取为 constexpr int 111222分别来自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;
}

可能的解决方案:

#include<utility>
#include<type_traits>

template <typename Tag, int v>
struct Const { static constexpr int value = v; };

struct T1 {};
struct T2 {};

struct Compound: Const<T1, 111>, Const<T2, 222> { };

template <typename Tag, int N>
constexpr auto f(Const<Tag, N>) {
    return std::integral_constant<int, N>{};
};

int main() {
    static_assert((111 == decltype(f<T1>(std::declval<Compound>()))::value), "!");
    static_assert((222 == decltype(f<T2>(std::declval<Compound>()))::value), "!");
}

您可以再添加一个函数来捕获常量,并在需要时return它。