[英]Problem in GCC/C++17 with template template class
考慮以下 2 個重載
template<typename T>
bool test() {
return true;
}
template<template<typename ...> class T>
bool test() {
return false;
}
第一個適用於常規類,而第二個適用於未實例化的模板。 例如:
std::cout<<test<int>()<<std::endl; <-- this yields 1
std::cout<<test<std::list>()<<std::endl; <--this yields 0
現在考慮以下模板函數:
template<typename U>
bool templfun(){
struct A{
bool f(){
return test<A>(); // <-- this gives an error
}
};
return test<A>(); // <-- this is ok
}
在 GCC 中,它為不明確的重載解析提供錯誤,而 Clang 編譯。 有趣的是,第二次調用 test() 不會產生錯誤(即使在 GCC 中)。 此外,如果我刪除了 templfun 之上的template<typename U>
東西,gcc 就會停止抱怨。
這是 GCC 的錯誤還是非法代碼?
海灣合作委員會是錯誤的; struct A
是模板化實體,但顯然不是模板(因為它不以template
關鍵字開頭),因此沒有歧義。
為了確認,我們可以重命名類型參數以查看 G++ 正在嘗試使用模板模板重載。
template <typename X>
bool test() {
return true;
}
template <template <typename...> class Y>
bool test() {
return false;
}
template <typename U>
bool templfun() {
struct A {
bool f() {
return test<A>(); // <-- this gives an error
}
};
return test<A>(); // <-- this is ok
}
bool run() {
return templfun<int>();
}
G++ 輸出:(鏈接到 Godbolt )
<source>:15:27: error: call of overloaded 'test<templfun() [with U = int]::A>()' is ambiguous
15 | return test<A>(); // <-- this gives an error
| ~~~~~~~^~
<source>:2:6: note: candidate: 'bool test() [with X = templfun() [with U = int]::A]'
2 | bool test() {
| ^~~~
<source>:7:6: note: candidate: 'bool test() [with Y = templfun()::A]'
7 | bool test() {
| ^~~~
顯然“ candidate: 'bool test() [with Y = templfun()::A]'
”是假的。
請注意,在 C++11 之前,不允許將本地類型作為模板參數(參見 C++03 § 14.3.1.2),因此這可以解釋 G++ 實現的復雜性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.