![](/img/trans.png)
[英]g++ and clang++ different behaviour with SFINAE and SFINAE failure
[英]g++ and clang++ different behaviour with variable template and SFINAE
另一個問題是“g ++和clang ++之間誰是對的?” 對於C ++標准大師。
假設我們希望將SFINAE應用於變量模板,以便僅在模板類型滿足特定條件時啟用變量。
例如:啟用bar
if(且僅當)模板類型具有帶給定簽名的foo()
方法。
通過具有默認值的其他模板類型使用SFINAE
template <typename T, typename = decltype(T::foo())>
static constexpr int bar = 1;
適用於g ++和clang ++,但有一個問題:可以被劫持,解釋第二個模板類型
所以
int i = bar<int>;
給出了編譯錯誤
int i = bar<int, void>;
編譯沒有問題。
所以,從我對SFINAE的無知的底部,我嘗試啟用/禁用相同變量的類型:
template <typename T>
static constexpr decltype(T::foo(), int{}) bar = 2;
驚喜:這對g ++有用(編譯)但是clang ++不接受它並給出以下錯誤
tmp_003-14,gcc,clang.cpp:8:30: error: no member named 'foo' in 'without_foo'
static constexpr decltype(T::foo(), int{}) bar = 2;
~~~^
像往常一樣,問題是:誰是對的? g ++或clang ++?
換句話說:根據C ++ 14標准,SFINAE可以用於變量模板的類型嗎?
以下是一個完整的例子
#include <type_traits>
// works with both g++ and clang++
//template <typename T, typename = decltype(T::foo())>
//static constexpr int bar = 1;
// works with g++ but clang++ gives a compilation error
template <typename T>
static constexpr decltype(T::foo(), int{}) bar = 2;
struct with_foo
{ static constexpr int foo () { return 0; } };
struct without_foo
{ };
template <typename T>
constexpr auto exist_bar_helper (int) -> decltype(bar<T>, std::true_type{});
template <typename T>
constexpr std::false_type exist_bar_helper (...);
template <typename T>
constexpr auto exist_bar ()
{ return decltype(exist_bar_helper<T>(0)){}; }
int main ()
{
static_assert( true == exist_bar<with_foo>(), "!" );
static_assert( false == exist_bar<without_foo>(), "!" );
}
讓我們來分析一下這里發生了什么:
我最初的假設是,這看起來像是一個鏗鏘的解釋。 當bar
未正確解析時,無法返回分辨率樹。
首先,為了確保問題出在bar
,我們可以這樣做:
template <typename T>
constexpr auto exist_bar_helper(int) -> decltype(void(T::foo()), std::true_type{});
它運作正常(SFINAE正在履行其職責)。
現在,讓我們更改您的代碼以檢查嵌套的失敗分辨率是否被外部SFINAE上下文包裝。 更改bar
后的功能:
template <typename T>
static constexpr decltype(void(T::foo()), int{}) bar();
它仍然正常,很酷。 然后,我會假設我們的decltype
中的任何不正確的解決方案將返回並使該函數解析為SFINAE回退(std :: false_type)...但不是。
這就是GCC的作用:
exist_bar -> exists_bar_helper -> bar (woops) -> no worries, i have alternatives
-> exists_bar_helper(...) -> false
這就是CLANG的作用:
exist_bar -> exists_bar_helper -> bar (woops) // oh no
// I cannot access that var, this is unrecoverable error AAAAAAAA
它如此認真地忽略了上層環境中的后備。
簡而言之:對於模板化變量,SFINAE不是SFINAE,SFINAE本身就是一個編譯器,當編譯器試圖“太聰明”時它會以奇怪的方式運行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.