問題描述
考慮以下代碼:
template <typename... Types>
struct list
{
template <typename... Args>
list(Args...)
{
static_assert(sizeof...(Types) > 0);
}
};
template <typename... Args>
list(Args...) -> list<Args...>;
int main()
{
list l{0, 0.1, 'a'};
}
我希望 decltype(l)
是 list
.不幸的是,g++ 7.2 和 g++ trunk 未能通過靜態斷言.clang++ 5.0.0 和 clang++ trunk 編譯并按預期工作.
I would expect decltype(l)
to be list<int, double, char>
. Unfortunately, g++ 7.2 and g++ trunk fail the static assertion. clang++ 5.0.0 and clang++ trunk compile and work as expected.
godbolt.org 一致性視圖
這是一個 g++ 錯誤嗎?或者有什么理由不應該在這里遵循演繹指南?
Is this a g++ bug? Or Is there a reason why the deduction guide should not be followed here?
在構造函數上添加 SFINAE 約束似乎提供了所需的行為:
Adding a SFINAE constraint on the constructor seems to provide the desired behavior:
template <typename... Args,
typename = std::enable_if_t<sizeof...(Args) == sizeof...(Types)>>
list(Args...)
{
static_assert(sizeof...(Types) > 0);
}
godbolt.org 一致性視圖
推薦答案
這是 gcc 錯誤 80871.問題是,我們最終得到了這組推演的候選對象:
This is gcc bug 80871. The issue is, we end up with this set of candidates for deduction:
template <class... Types, class... Args>
list<Types...> __f(Args... ); // constructor
template <class... Args>
list<Args...> __f(Args... ); // deduction-guide
兩者都是有效的(Types...
在第一種情況下可以推斷為空),但是這里的調用應該是模棱兩可的 - 兩者都不比另一個更專業.Types...
不參與這里的排序(類似于 [temp.deduct.partial]/12).所以正確的行為是繼續下一個決勝局,它贊成演繹指南.因此,這應該是一個 list
.
Both are valid (Types...
can deduce as empty in the first case), but the call here should be ambiguous - neither is more specialized than the other. Types...
does not participate in ordering here (similar to the example in [temp.deduct.partial]/12). So the correct behavior is to proceed to the next tiebreaker, which favors deduction-guides. Hence, this should be a list<int, double, char>
.
然而,gcc 的行為是有利于構造函數,因此 static_assert
觸發器因為 Types...
在這種情況下確實是空的.
However, gcc's behavior is to favor the constructor, hence the static_assert
triggers becuase Types...
would indeed be empty in that situation.
這篇關于g++ 不采用可變參數推導指南,clang++ 采用-誰是正確的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!