some_class如果類是模板化的,則以下代碼不起作用。所以我的猜測是我必須把說明template符放在前面,但我真的不知道在哪里?我嘗試將它放在變體定義中的 state::base 和 state::error 型別的前面,但這不起作用。我把它放在哪里,為什么?
演示
#include <variant>
template <typename T>
class some_class
{
void do_something() {
struct state {
struct base{};
struct error{};
};
std::variant<state::base, state::error> fsm{};
}
};
int main() {}
錯誤:
<source>:12:47: error: type/value mismatch at argument 1 in template parameter list for 'template<class ... _Types> class std::variant'
12 | std::variant<state::base, state::error> fsm{};
| ^
<source>:12:47: note: expected a type, got 'some_class<T>::do_something()::state::base'
<source>:12:47: error: type/value mismatch at argument 1 in template parameter list for 'template<class ... _Types> class std::variant'
<source>:12:47: note: expected a type, got 'some_class<T>::do_something()::state::error'
uj5u.com熱心網友回復:
編譯器認為state::baseand依賴于state::error(依賴于模板引數),在這種情況下,它們需要前綴 with以便在決議類模板定義時將它們視為型別。typename
然而,直覺上這些名稱/型別似乎不應該依賴。盡管型別對于封閉類模板的每個特化都是不同的,但可以保證state::base在封閉模板的每個實體化的函式定義中始終命名和參考已知型別。這不能改變,例如通過顯式或部分特化。
這似乎是一個開放的 CWG 問題(CWG 2074)。該標準目前沒有說這些名稱是依賴的。僅當本地類包含依賴型別(請參閱[temp.dep.type]/9.5)時,它們才會依賴,但在您的情況下它們不會這樣做。仍然似乎一些編譯器認為這些型別是依賴的。
因此,您的解決方案是在它們前面加上前綴,typename即使這可能不是標準所要求的或不打算的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515140.html
標籤:C 模板c 20依赖名称
上一篇:如何定義依賴于模板引數的型別
