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 ?
}
正如我最近了解到,在查找期间基类中的名称之后会检查模板派生类的模板参数。话虽如此,无论如何限定名称T
初始化value
以引用派生类的模板参数T
?
编辑:
到目前为止,评论中的讨论似乎是实现这一点的唯一方法是使基类类型/值依赖,这将延迟查找基数的名称(到实例化阶段),从而使只有T的可用值是模板参数。
答案 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;
}