C ++模板继承隐藏模板参数

时间:2018-06-01 08:21:48

标签: c++ c++11 templates

template <typename>
struct B
{
    constexpr static int T = 5;
};

template <int T>
struct D : B<int>
{
    constexpr static int value = T;
};

int main()
{
    std::cout << D<7>::value << std::endl; // 5, how to get 7 ?
}

Demo

正如我最近了解到,在查找期间基类中的名称之后会检查模板派生类的模板参数。话虽如此,无论如何限定名称T初始化value以引用派生类的模板参数T

编辑:

到目前为止,评论中的讨论似乎是实现这一点的唯一方法是使基类类型/值依赖,这将延迟查找基数的名称(到实例化阶段),从而使只有T的可用值是模板参数。

3 个答案:

答案 0 :(得分:8)

我不完全确定我理解这个问题,但我认为decltype可以做你想要的:

template <int T>
struct D : B<decltype(T)>
{
    constexpr static decltype(T) value = T;
};

答案 1 :(得分:1)

由于B是模板,因此您可以修改它以使其成为D的依赖基类:

template <typename, int = 0>
struct B {
    constexpr static int T = 5;
};

template <int T>
struct D : B<int, T> {
    constexpr static int value = T; // name lookup of base T is deferred
};

答案 2 :(得分:0)

引用模板T的值B(它不依赖于B的模板参数):

#include <iostream>

template <typename>
struct B
{
    constexpr static int T = 5;
};

template <int T>
struct D : B<decltype(B<void>::T)>
{
    constexpr static int value = T;
};

int main()
{
    std::cout << D<7>::value << std::endl;
}

引用模板T的模板参数D的类型:

#include <iostream>

template <typename>
struct B
{
    constexpr static int T = 5;
};

template <int T>
struct D : B<decltype(T)>
{
    constexpr static int value = T;
};

int main()
{
    std::cout << D<7>::value << std::endl;
}