2

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  
Jerry
  • 117
  • 6

1 Answers1

3

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;
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 1
    why did you declare struct B instead of class B in the beginning? – Jerry Sep 15 '22 at 10:02
  • 2
    @Jerry because it doesnt matter. When I don't need it to be `class` then I am used to type `struct`, but it makes no difference here – 463035818_is_not_an_ai Sep 15 '22 at 10:03
  • @463035818_is_not_a_number Are you sure this is allowed by C++? Not that it breaks the example but `struct B` is not the same as `class B`, right? Declaring `struct B* ptr;` and doing `class B{}; ptr= new B{};` is not correct C++, is it? – Quimby Sep 15 '22 at 10:10
  • @Quimby it is correct. `class` and `struct` are just two keywords to declare a class. Really the only difference is default access for members and default inheritance, but both are irrelevant for the forward declaration. https://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c – 463035818_is_not_an_ai Sep 15 '22 at 10:26
  • ...anyhow its not the topic of this question so I changed to `class` – 463035818_is_not_an_ai Sep 15 '22 at 10:28
  • @Quimby given a forward declaration of some class `B` you cannot possibly distinguish if it was declared via `struct B;` or `class B;` – 463035818_is_not_an_ai Sep 15 '22 at 10:28