在某些情况下,decltype(auto)与SFINAE一起使用?

Cur*_*ous 3 c++ sfinae c++17

我假设这decltype(auto)是一个不兼容的结构,当用于尝试和返回类型的SFINAE.所以,如果你原本会遇到替换错误,那么你会遇到一个很难的错误

但为什么以下程序有效?https://wandbox.org/permlink/xyvxYsakTD1tM3yl

#include <iostream>
#include <type_traits>

using std::cout;
using std::endl;

template <typename T>
class Identity {
public:
  using type = T;
};

template <typename T>
decltype(auto) construct(T&&) {
  return T{};
}

template <typename T, typename = std::void_t<>>
class Foo {
public:
  static void foo() {
    cout << "Nonspecialized foo called" << endl;
  }
};
template <typename T>
class Foo<T,
          std::void_t<typename decltype(construct(T{}))::type>> {
public:
  static void foo() {
    cout << "Specialized foo called" << endl;
  }
};

int main() {
  Foo<Identity<int>>::foo();
  Foo<int>::foo();
}
Run Code Online (Sandbox Code Playgroud)

我们不应该在Foo实例化时遇到硬错误int吗?鉴于int没有名为type?的成员别名?

Bar*_*rry 5

我假设这decltype(auto)是一个不兼容的结构,当用于尝试和返回类型的SFINAE.

它通常是不兼容的,因为它强制函数体的实例化.如果在正文中发生替换失败,则这将是一个硬编译错误 - SFINAE不适用于此处.

但是,在此示例中,您在主体中获得替换失败的唯一方法是,如果T不是默认可构造的.但是你调用construct T{},它已经要求它是默认的可构造的 - 所以失败将首先发生或永远发生.

相反,发生的替代失败是在替代的直接背景下typename decltype(construct(T{}))::type.当我们处于实例化模板参数的直接上下文中时,试图::type摆脱这种int情况发生Foo,因此SFINAE仍然适用.

一个例子展示decltype(auto)了SFINAE 在哪里休息,如果我们将其实现为:

template <typename T>
decltype(auto) construct() {
  return T{};
}

template <typename T, typename = std::void_t<>>
class Foo {
public:
  static void foo() {
    cout << "Nonspecialized foo called" << endl;
  }
};
template <typename T>
class Foo<T,
          std::void_t<typename decltype(construct<T>())::type>> {
public:
  static void foo() {
    cout << "Specialized foo called" << endl;
  }
};
Run Code Online (Sandbox Code Playgroud)

然后尝试实例化:

struct X {
    X(int);
};

Foo<X>::foo(); // hard error, failure is in the body of construct()
Run Code Online (Sandbox Code Playgroud)

  • @Curious 因为现在 `T{}` 首先在直接上下文中。 (2认同)