简体   繁体   中英

Declaring a template class as friend

Here is an 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>; 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>; was right, but it needs a declaration of 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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