c++ - 从非成员模板函数访问私有(private)内部类类型

标签 c++ templates private inner-classes

考虑以下代码:

#include <iostream>
using namespace std;

class Outer {
    struct Inner {
        int num;    
    };

public:
 static Inner GetInner() {
    return Inner{-101};
}
};

// void func1(Outer::Inner inner) {  // [1] Does not compile as expected
//  cout << inner.num <<endl;
//}

template <typename Dummy>
void func2(Outer::Inner inner, Dummy = Dummy()) {
    cout << inner.num << endl;
}


int main() {
    // func1(Outer::GetInner()); // [2] does not compile as expected 
    func2<int>(Outer::GetInner()); // [3] How does this compile? 
                                   // Outer::Inner should not be accessible
                                   // from outside Outer
    return 0;
}

我如何能够在非成员函数 func2 中使用私有(private)类型 Outer::Inner 的参数? 'func1 当我尝试使用它并出现以下错误消息时,它理所当然地提示:

prog.cpp: In function 'void func1(Outer::Inner)':
prog.cpp:5:9: error: 'struct Outer::Inner' is private
  struct Inner {
         ^
prog.cpp:15:19: error: within this context
 void func1(Outer::Inner inner) {
               ^

我在 ubuntu 上使用 g++4.8.2,但我也在 gcc-4.9.2(在 www.ideone.com 上)上看到了这个

您可以在此处试用代码:Ideone

最佳答案

我明白了

Error 1 error C2248: 'Outer::Inner' : cannot access private struct declared in class 'Outer'

使用 Visual Studio 2013 update 4。因此,这是您的编译器中的问题。

关于c++ - 从非成员模板函数访问私有(private)内部类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596242/

相关文章:

Python OpenSSL 生成公钥和私钥对

c++ - gcc 和 clang 上奇怪的嵌套类部分特化结果

c++ - 使用 boost::mpl::bool_ 而不是 const bool 的优点

c++ - 求旋转椭圆的角度

c++ - 具有实际独立的依赖表达式的 static_assert

c++ - 统一扩展两个参数包

ios - 当 iOS 中的简单实例变量完成相同的工作时,为什么我们在 .m 文件中创建私有(private)属性?

private - PubNub 最佳实践 : How to manage private rooms?

c++ - 为 64 位编译 Microsoft Detours

c++ - 将项目源代码与 CMake 下的 boost 测试链接起来