c++ - 模板嵌套私有(private)类作为 friend

标签 c++ templates gcc

我有以下代码不能在 GCC 4.9 和 GCC 5.1 上编译。我似乎无法弄清楚为什么。抱歉,如果这是一个菜鸟问题,我是 C++ 模板的新手。

template<class T>class A
{
    template<class X>friend class B;
    struct C {};
};

template<class X>class B 
{
    template<class T>friend struct A<T>::C;
};

int main()
{
    A<int> a;
    B<float> b;
}

编译时出现如下错误

root@localhost# g++-49 templatefriend.cpp
templatefriend.cpp: In instantiation of âclass B<float>â:
templatefriend.cpp:38:9:   required from here
templatefriend.cpp:27:9: error: âstruct A<T>::Câ is private
  struct C {};
     ^
templatefriend.cpp:31:1: error: within this context
 {
 ^

如果我删除模板,编译会很好

class A
{
    friend class B;
    class C{};
};

class B
{
    friend class A::C;
};

int main()
{
    A a;
    B b;
}

感谢任何帮助,或者如果已经有人问过这样的问题,请分享链接。

最佳答案

在这种情况下,您从 clang 获得的警告会更有帮助:

warning: dependent nested name specifier 'A<X>::' for friend class declaration is not supported

换句话说,A::C 是一个依赖类型,所以它不起作用(虽然我不知道在标准中的什么地方描述了这一点。

我怀疑实际上您只希望关系介于 A<T> 之间。和 B<T>其中 T是相同的(例如 A<int>B<int> 但不是 A<char>B<float> )。如果是这种情况,您可以通过在友元声明中使用相同的模板参数来完成此操作

template <typename T> class B;

template<class T>
class A {
    friend class B<T>;  // B of the same templated type is my friend
    struct C {};
};

template<class T>
class B {
    friend struct A<T>::C; // A::C of the same templated type is my friend
};

另一种选择是 template <typename> class A; B 内部,这也会使 A::C一个 friend 。

关于c++ - 模板嵌套私有(private)类作为 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30882847/

相关文章:

c++ - gcc 的 -Wconversion 是否与使用比 int 短的整数类型的复合赋值(+= 等)不兼容?

c - 结构初始化符号不适用于堆分配的存储

c++ - 递归(从 2 到(2 乘以 n)的偶数之和 ex : input : n=6, 输出:2+4+6

c++ - 如何设置:hover on QMenu?

c++ - 类模板特化的前向声明

c++ - 将 C++ 模板类型限制为特定的变量大小

c++ - gcc 版本显示 4.2.1 即使在安装 4.9 (Homebrew) 之后

c++ - 头文件中的 "class X;"是什么意思?

c++ - 检查模板参数是否为引用 [C++03]

c++ - 推断 CRTP 中模板化成员函数的返回类型