简体   繁体   English

从非成员模板函数访问私有内部类类型

[英]Accessing private inner class type from non-member template function

Consider the following code: 考虑以下代码:

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

How is it that I am able to use an argument of type Outer::Inner , which is a private type, in the non-member function func2 ? 我如何在非成员函数func2使用类型为Outer::Inner的参数,这是一个私有类型? ' func1 rightfully complains when I try and use it with the following error message: 当我尝试将其与以下错误消息一起使用时, 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) {
               ^

I am using g++4.8.2 on ubuntu, but I also see this on gcc-4.9.2 (on www.ideone.com) 我在ubuntu上使用g ++ 4.8.2,但我也在gcc-4.9.2(在www.ideone.com上)上看到了

You can try out the code here: Ideone 您可以在此处尝试代码: Ideone

I get 我懂了

Error 1 error C2248: 'Outer::Inner' : cannot access private struct declared in class 'Outer' 错误1错误C2248:“ Outer :: Inner”:无法访问在“ Outer”类中声明的私有结构

using Visual Studio 2013 update 4. Ergo, it is a problem in your compiler. 使用Visual Studio 2013更新4。嗯,这是您的编译器中的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将调用 class 的“this”或“type”隐式传递给非成员模板 function - Implicitly pass the "this" OR the "type" of the calling class to a non-member template function 哪里放置一个PRIVATE嵌套(内部)类的非成员函数定义? - Where to put non-member function definition of a PRIVATE nested (inner)class? 将模板类实例类型别名传递给非成员模板函数 - Pass template class instance type alias to non-member template function 使用(非类型)枚举参数定义内部类成员函数模板 - Defining an Inner class member function template with a (non type) enum argument 模板类成员与非成员模板函数的歧义 - Template class member vs. non-member template function ambiguity 非会员经营者作为外国舱的私人会员 - Non-member operator as private member of foreign class 选择使某个功能成为成员,非成员,私有,公共等 - Choosing to make a function a member, non-member, private, public, etc 在非成员函数中访问MFC对话框的成员变量 - Accessing member variables of MFC dialog in non-member function 绑定非成员 static function 与成员 function 一起的模板 - Template to Bind non-member static function alongside with member function 为模板化内部类重载非成员运算符 - Overloading of a non-member operator for a templated inner class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM