![](/img/trans.png)
[英]Implicitly pass the "this" OR the "type" of the calling class to a non-member template function
[英]Accessing private inner class type from non-member template function
考慮以下代碼:
#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
我懂了
錯誤1錯誤C2248:“ Outer :: Inner”:無法訪問在“ Outer”類中聲明的私有結構
使用Visual Studio 2013更新4。嗯,這是您的編譯器中的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.