本文介绍了vc ++ 10中的模板私有继承不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用GCC 4.4.6和Comeau 4.3.10编译。

The following code compiles using GCC 4.4.6 and Comeau 4.3.10.

#include <iostream>

struct A { int name; };
template<typename T> struct C : T { using T::name; };
struct B : private A { friend struct C<B>; };

int main()
{
    C<B> o;
    o.name = 0;
}

在VC ++ 10中会出现以下错误:

It gives the following error in VC++10:

main.cpp(4): error C2877: 'A::name' is not accessible from  'A'
main.cpp(10): error C2247: 'A::name' not accessible because 'B' uses 'private' to inherit from 'A'


什么是一个好的交叉编译器解决方法,允许 o.name = 0; ?

What's a good cross-compiler workaround that allows o.name = 0;?

注意:使用A :: name 添加到 B 处理问题,但将 A :: name 成员发布给每个人,而它应该只对特定的模板实例可见,即 C

Note: Adding using A::name to B takes care of the problem, but publishes the A::name member to everyone, whereas it should only be visible to a particular template instantiation, namely C<B>.

推荐答案

kerrekSB建议,在 B 中使用A :: name添加:

Work around is what @kerrekSB suggested, add using A::name; in class B:

struct A { int name; };
template<typename T> struct C : T { using T::name; };

struct B : private A {
using A::name;
friend struct C<B>;
};

您的初始示例没有工作,因为class A 是 B 是 B ,但是当您从 C 的对象访问成员 name 时,使用T :: name; 创建问题,因为 B 类没有任何成员 name 。当您尝试通过 B

your initial example didn't work cause class A is private to B and class C<B> is friend of B but when you access member name from object of C<B> , line using T::name; creates problem since the class B doesn't has any member name in it. it's scope search which find the member name when you try to access it via object of class B

编辑:

如果是这种情况,那么在类 B >

if that's the case , then simply declare statement using A::name; in private section in class B i.e

struct B : private A {
protected: using A::name;
public:
friend struct C<B>;
};

这篇关于vc ++ 10中的模板私有继承不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:57