[英]C++ template inheritance hides template parameters
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
?
編輯:
到目前為止,評論中的討論似乎是實現這一點的唯一方法是使基類類型/值依賴,這將延遲查找基數的名稱(到實例化階段),從而使唯一可用的值for T是模板參數。
我不完全確定我理解這個問題,但我認為decltype
做你想要的:
template <int T>
struct D : B<decltype(T)>
{
constexpr static decltype(T) value = T;
};
因為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
};
要引用模板B
值T
(不依賴於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;
}
要引用模板D
的模板參數T
的類型:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.