简体   繁体   中英

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 ? ' func1 rightfully complains when I try and use it with the following error message:

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)

You can try out the code here: Ideone

I get

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

using Visual Studio 2013 update 4. Ergo, it is a problem in your compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM