使用私有嵌套类型的Friend操作符函数仅在MSVC中失败

时间:2014-03-26 19:59:49

标签: c++ visual-c++ friend

我一直在搜索和试验,我无法弄清楚MSVC编译器是错误还是我做错了。

我已将案例简化为一组最小的声明,不需要任何包含的标题:

// A namespace.
namespace TestNamespace
{
  // And a class inside that.
  class TestClass
  {
  private:
    // Note that we're private
    struct NestedEnum {
      enum type {
        First,
        Second,
        Third,
      };
    };

    // Test friend declaration.
    friend void operator<<(int, const NestedEnum::type);
  };

  // Actual declaration.  It can't be earlier because of NestedEnum.
  void operator<<(int, const TestClass::NestedEnum::type);
}

// Actual definition, outside of the TestNamespace block, but scoped to be
// in the namespace.
void TestNamespace::operator<<(int, const TestClass::NestedEnum::type)
{}

使用MSVC,我得到:

cl.exe foo.cc
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.61030 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

foo.cc
foo.cc(27) : error C2248: 'TestNamespace::TestClass::NestedEnum' : cannot access private struct declared in class 'TestNamespace::TestClass'
    foo.cc(9) : see declaration of 'TestNamespace::TestClass::NestedEnum'
    foo.cc(6) : see declaration of 'TestNamespace::TestClass'

gcc 4.7.2和clang-425.0.28都接受这个(以及更复杂的实例)。

1 个答案:

答案 0 :(得分:0)

根据Rastaban的评论,这是编译器中的一个错误。