g ++和clang ++使用变量模板和SFINAE的不同行为

max*_*x66 6 c++ templates sfinae c++14 template-variables

另一个问题是"g ++和clang ++之间谁是对的?" 对于C++标准大师.

假设我们希望将SFINAE应用于变量模板,以便仅在模板类型满足特定条件时启用变量.

例如:启用barif(且仅当)模板类型具有foo()给定签名的方法.

通过具有默认值的其他模板类型使用SFINAE

template <typename T, typename = decltype(T::foo())>
static constexpr int bar = 1;  
Run Code Online (Sandbox Code Playgroud)

适用于g ++和clang ++,但有一个问题:可以被劫持,解释第二个模板类型

所以

int i = bar<int>;
Run Code Online (Sandbox Code Playgroud)

给出了编译错误

int i = bar<int, void>;
Run Code Online (Sandbox Code Playgroud)

编译没有问题.

所以,从我对SFINAE的无知的底部,我尝试启用/禁用相同变量的类型:

template <typename T>
static constexpr decltype(T::foo(), int{}) bar = 2; 
Run Code Online (Sandbox Code Playgroud)

惊喜:这对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;
                          ~~~^
Run Code Online (Sandbox Code Playgroud)

像往常一样,问题是:谁是对的?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>(), "!" );
 }
Run Code Online (Sandbox Code Playgroud)

Iva*_*asa -1

让我们分析一下这里发生了什么:

我最初的假设是,这看起来像是对 clang 的误解。bar当未正确解析时,它无法返回到解析树中。

首先,为了确定问题出在 中bar,我们可以这样做:

template <typename T>
constexpr auto exist_bar_helper(int) -> decltype(void(T::foo()), std::true_type{});
Run Code Online (Sandbox Code Playgroud)

它工作正常(SFINAE 正在做它的工作)。

现在,让我们更改代码以检查嵌套的失败解决方案是否由外部 SFINAE 上下文包装。bar改成函数后:

template <typename T>
static constexpr decltype(void(T::foo()), int{}) bar();
Run Code Online (Sandbox Code Playgroud)

它仍然可以正常工作,很酷。然后,我假设我们内部的任何不正确的解析decltype都会返回并使函数解析为 SFINAE 后备(std::false_type)...但是不是。

这就是海湾合作委员会所做的:

exist_bar -> exists_bar_helper -> bar (woops) -> no worries, i have alternatives
          -> exists_bar_helper(...) -> false
Run Code Online (Sandbox Code Playgroud)

这就是 CLAN 所做的:

exist_bar -> exists_bar_helper -> bar (woops) // oh no
// I cannot access that var, this is unrecoverable error AAAAAAAA
Run Code Online (Sandbox Code Playgroud)

它如此认真地对待它,以至于忘记了上层上下文中的后备。

长话短说:不要对模板变量使用 SFINAE,SFINAE 本身就是一个编译器 hack,当编译器试图变得“太聪明”时,它会以奇怪的方式表现