代码之家  ›  专栏  ›  技术社区  ›  apmccartney

使用void\u t和受保护嵌套类的基于SFINAE的检测

  •  7
  • apmccartney  · 技术社区  · 7 年前

    最近,我遇到了一些clang和gcc之间关于 void_t 属性检测和受保护/私有类信息。考虑一个类型特征定义如下:

    #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;
    

    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编译失败,发出诊断。此错误可在魔杖盒上重现 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{};
                  ^~~~
    

    1 回复  |  直到 7 年前
        1
  •  4
  •   Igor R.    7 年前

    这是一个 GCC bug . 这是世界的一部分 following meta-bug

    推荐文章