简体   繁体   English

将模板 class 声明为好友

[英]Declaring a template class as friend

Here is an MCVE:这是一个 MCVE:

template <typename T>
class A {
public:
    friend class B;
};

template <typename T>
class B {};

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

Very simple thing and I dont know why this is giving compiler errors.非常简单的事情,我不知道为什么这会导致编译器错误。 I am new to using templates.我是使用模板的新手。 I also tried changing the friend declaration to friend class B<T>;我还尝试将朋友声明更改为friend class B<T>; but that gave other errors, and did not work as well.但这给出了其他错误,并且效果不佳。

Here is the errors that the compiler is throwing for the above code:以下是编译器为上述代码抛出的错误:

1> Error    C2989   'B': class template has already been declared as a non-class template   D:\Projects\1.C++\test\test\test.cpp    8
2> Error    C3857   'B': multiple template parameter lists are not allowed  test    D:\Projects\1.C++\test\test\test.cpp    7
3> Error    C2059   syntax error: '<'   test    D:\Projects\1.C++\test\test\test.cpp    12  

It depends on what you want, if you want to make B<T> a friend of A<T> then friend class B<T>;这取决于你想要什么,如果你想让B<T>成为A<T> <T> 的朋友,那么friend class B<T>; was right, but it needs a declaration of B :是对的,但它需要声明B

template <typename T> class B;

template <typename T>
class A {
public:
    friend class B<T>;
};

template <typename T>
class B {};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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