簡體   English   中英

帶有const和模板參數的gcc中的錯誤?

[英]Bug in gcc with const& template parameters?

考慮以下代碼:

#include <type_traits>

template < int > struct II { };
template < const int& > struct RR { };

template < template <auto> typename Class, typename Type > struct Check : std::false_type { };
template < template <auto> typename Class, auto NonTypes > struct Check<Class,Class<NonTypes>> : std::true_type { };

constexpr int TEN = 10;
constexpr const int& REF = TEN;

static_assert(Check<II,II<TEN>>::value); // passes
static_assert(Check<RR,RR<REF>>::value); // FAILS!?

我正在使用gcc-7.0.1, 是實例。 問題是,這是一個編譯器錯誤還是我做錯了什么?

讓我們簡化一下這個例子:

template <template <auto> class C, auto N>
void foo(C<N> ) { }

int main() {
    foo(II<TEN>{} ); // ok
    foo(RR<REF>{} ); // error
}

問題是正常的auto扣除規則適用於N ,它在REF情況下推斷為int類型。 非類型模板參數類型 - int const& - 和參數 - int之間存在不匹配,因此它是不正確的。

如果我們將示例翻轉為auto const& N (或auto&& N ),那么它就是II<TEN>調用,由於同樣的原因,它將是錯誤的 - 我們現在得到一個引用類型的模板參數但參數是非引用類型。

您無法使用當前語言中的一個函數來處理這兩種情況。 你需要兩個:

template <template <auto> class C, auto N>     void foo(C<N> ) { } // #1
template <template <auto&&> class C, auto&& N> void foo(C<N> ) { } // #2

int main() {
    foo(II<TEN>{} ); // ok: calls #1
    foo(RR<REF>{} ); // ok: calls #2
}

與原始示例類似:您需要一個值專門化和一個引用專門化。 C的模板 - 模板非類型參數中的引用可能不是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM