c++ - 使用 void_t 和 protected 嵌套类进行基于 SFINAE 的检测

标签 c++ gcc c++17 detection void-t

我最近在 void_t 属性检测和 protected /私有(private)类信息方面遇到了 clang 和 gcc 之间的一些不同行为。考虑如下定义的类型特征:

#include <type_traits>

template<typename T, typename = void>
constexpr const bool has_nested_type_v = false;

template<typename T>
constexpr const bool has_nested_type_v
<T, std::void_t<typename T::type>> = true;

给定具有 protected 或私有(private)嵌套 type 类的示例类型和一个简单的程序

#include "has_nested_type.hpp"
#include <iostream>

struct Protected {
protected:
  struct type{};
};

struct Private {
private:
  struct type{};
};

int main() {
  std::cout << "Protected: " 
            << (has_nested_type_v<Protected> ? "detected" : "not detected")
            << std::endl;
  std::cout << "Private: " 
            << (has_nested_type_v<Private> ? "detected" : "not detected")
            << std::endl;
}
  • clang 编译成功但检测失败(如预期)。程序、编译、输出转载于wandbox here .

  • gcc 编译失败,发出诊断信息。可以在 wandbox 上重现此错误 here .

GCC 为该程序发出以下错误。

prog.cc:16:21: error: 'struct Protected::type' is protected within this context
                 << (has_nested_type_v<Protected> ? "detected" : "not detected")
                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
prog.cc:6:14: note: declared protected here
       struct type{};
              ^~~~
prog.cc:19:21: error: 'struct Private::type' is private within this context
                 << (has_nested_type_v<Private> ? "detected" : "not detected")
                     ^~~~~~~~~~~~~~~~~~~~~~~~~~
prog.cc:11:14: note: declared private here
       struct type{};
              ^~~~

我的问题是哪种行为符合标准?应该在此处发出 clang 错误并发出诊断信息,还是 GCC 过于急切?

最佳答案

这是一个 GCC bug .它是 following meta-bug 的一部分描述了几个与访问相关的错误。

关于c++ - 使用 void_t 和 protected 嵌套类进行基于 SFINAE 的检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53917846/

相关文章:

c++ - [[nodiscard]] 在 std::function 返回类型定义中?

c++ - 如何从 C++ 模板中解压 std::tuple?

c++ - C++中引用和指针返回类型之间的区别是什么

c++ - 专门化后的显式实例化

c++ - 两个相关的类层次结构——覆盖虚函数

c++ - 内联静态数据导致节类型冲突

c++ - 作为数据类型出现的纯虚类?

c - 如何在 gcc 中正确使用 __attribute__((fallthrough))

c++ - 包括 boost function.hpp,但不使用它,会使我的二进制文件的大小增加 200k。为什么?

c++ - std C++ 17不支持CPPUNIT吗?