C++ C++;模板继承隐藏模板参数 模板 结构B { constexpr static int T=5; }; 模板 结构D:B { constexpr静态int值=T; }; int main() { std::cout
因为C++ C++;模板继承隐藏模板参数 模板 结构B { constexpr static int T=5; }; 模板 结构D:B { constexpr静态int值=T; }; int main() { std::cout,c++,c++11,templates,C++,C++11,Templates,因为B是模板,所以可以修改它使其成为D的依赖基类: 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 <<
B
是模板,所以可以修改它使其成为D
的依赖基类:
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 ?
}
#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;
}
模板
结构B{
constexpr static int T=5;
};
模板
结构D:B{
constexpr static int value=T;//推迟了对基T的名称查找
};
我不完全确定我是否理解这个问题,但我认为decltype
符合您的要求:
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
};
模板
结构D:B
{
constexpr静态decltype(T)值=T;
};
参考模板B
的值T
(不依赖于B
的模板参数):
直到…有趣的问题。
B
不需要成为模板顺便说一句,一个简单的类
也有同样的行为。如果我理解这个问题,你不能为模板参数使用一个不同的名称吗?如果你不知道基声明了什么呢?换句话说,你想检查B::t
,不是吗?实际上,你正在解决OP的问题,value
等于模板参数T
,而不是baseT
。什么…哦,你在人为地使B
依赖于T
,这样它的范围就不会被考虑,除非符合条件…讨厌!而且你也不需要第二个decltype,因为它可以生成base class类型依赖于enough@Quentin你知道为什么decltype(T)
被认为是依赖的吗?无论如何,这解决了这个问题,但对我来说似乎是一个解决办法。我更喜欢某种方法来真正限定你想要的,而不是让基类类型依赖于类似的解决方案,但你让它依赖于值?
#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;
}
#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;
}