[英]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.