![](/img/trans.png)
[英]Use nested class of templated class as template template parameter in C++
[英]How can I use a nested type belonging to a templated class in another template function in C++?
我正在設置一個函數,它基於元組類型和函子結構來初始化元組。 For
它有一個size_t模板參數INDEX
來保留編譯時索引。 這個仿函數也可能依賴於其他模板參數T...
因此, TClass
函數存在於TClass
這些模板參數的其他結構(本示例中為TClass
)中。
初始化函數(此處稱為Bar
)具有template<std::size_t> class
模板參數,以確保所使用的類實際上可以存儲索引。
雖然當我從非模板函數調用它時,我提出的設計工作正常,但如果函數的模板T2
確定包裝器TClass
的模板參數,則它不會編譯。
這是functor的定義For
裹在TClass
:
#include <cstdlib>
template <typename T> struct TClass {
template<std::size_t INDEX> struct For {
void operator()() {}
};
};
以下是我想要使用的函數調用:
template <template<std::size_t> class FOR> void bar() {
//...
}
template <typename T> void foo() {
bar<TClass<T>::For>(); //Does not compile
}
int main() {
bar<TClass<int>::For>(); //Works
foo<int>();
return 0;
}
故障foo
-call的編譯器輸出是:
error: dependent-name ‘TClass<T>::For’ is parsed as a non-type, but instantiation yields a type
Bar<TClass<T>::For>(); //Does not compile
我知道依賴類型名稱通常必須以typename
開頭,但這對於第一個bar
-call也不是必需的。 我假設這是因為模板參數只能被解釋為一種類型。 所以我認為也許typename
會導致正確的編譯,但如果我改變foo
template <typename T> void foo() {
bar<typename TClass<T>::For>(); //Does not compile
}
我明白了:
error: ‘typename TClass<int>::For’ names ‘template<long unsigned int INDEX> struct TClass<int>::For’, which is not a type
Bar<typename TClass<T>::For>(); //Does not compile
我還想出了一個設計,其中TClass
的()
- 操作TClass
依賴於模板INDEX
,它也可以正常工作,因為它不再需要使用嵌套類型。 它看起來像這樣:
#include <cstdlib>
template <typename T> struct TClass {
template<std::size_t INDEX> void operator()() {}
};
template <typename FOR> void bar() {
//...
}
template <typename T> void foo() {
bar<TClass<T>>(); //Does compile
}
顯然,在函數模板參數確定類型模板的函數中,不可能使用依賴類型名稱,但為什么呢? 我該如何正確實現? 為了使用類型特征更容易編寫未來的類型檢查我更喜歡它,如果我可以使用仿函數。
編譯器無法知道TClass<T>::For
在模板實例化的第一階段引用模板。 它需要一些關於template
關鍵字的幫助。 固定:
template <typename T> void foo() {
bar<TClass<T>::template For>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.