【问题标题】:Accessing private inner class type from non-member template function从非成员模板函数访问私有内部类类型
【发布时间】:2015-04-20 04:47:22
【问题描述】:

考虑以下代码:

#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 中使用类型为私有类型的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

【问题讨论】:

  • 看起来像一个g++错误,你找到答案了吗?对我来说,它不应该是法律代码。

标签: c++ templates private inner-classes


【解决方案1】:

我明白了

错误 1 ​​错误 C2248:“Outer::Inner”:无法访问在“Outer”类中声明的私有结构

使用 Visual Studio 2013 更新 4。所以,这是你的编译器的问题。

【讨论】:

  • 谢谢!看起来 clang 有问题。
猜你喜欢
  • 1970-01-01
  • 2020-08-23
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2016-08-04
  • 1970-01-01
  • 2016-01-28
相关资源
最近更新 更多