ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-08-28 02:07:09  阅读:186  来源: 互联网

标签:c sfinae c17


我假设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();
}

当Foo用int实例化时,我们不应该得到一个硬错误吗?鉴于int没有名为type的成员别名?

解决方法:

I was under the assumption that decltype(auto) is an incompatible construct when used to try and SFINAE off the return type.

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

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

相反,发生的替换失败是在替换为typename decltype(construct(T {})):: type的直接上下文中.当我们处于将模板参数实例化为Foo的直接上下文中时,尝试从一个int中获取:: type,因此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;
  }
};

然后尝试实例化:

struct X {
    X(int);
};

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

标签:c,sfinae,c17
来源: https://codeday.me/bug/20190828/1746955.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有