0

In other words does this code work?

#include <iostream>

template <class T>
class ImFriendWith {
    int privValue;
    public:
        ImFriendWith(int v): privValue{v} {};
    
    friend class T; // <-- THIS
};

struct Befriended {
    ImFriendWith<Befriended> secret;
    
    Befriended(int v): secret{v} {};
    
    int getValue() { return secret.privValue; }
};

int main (int argc, char **argv)
{
    Befriended b{42};
    std::cout << "The secret is: " << b.getValue() << std::endl;
    return 0;
}

I tried to compile it with G++, but it splits out only errors. Also I haven't found anything like my example at https://en.cppreference.com/

However...

If I remove the text "class" next to "friend", then it compiles and works like I wanted: it prints "The secret is: 42".

I want to know:

  • why it works, and
  • is it portable?
Felix.leg
  • 622
  • 1
  • 4
  • 13
  • It's not clear to me exactly what you're asking. You posted code that fails to compile, and you know what to change to fix it. So what exactly is the problem? – Kevin Nov 10 '21 at 16:15
  • @Kevin Why it works. I haven't found anybody doing it, and any C++ specification that mentions something like my code. For all what I know it shouldn't work. – Felix.leg Nov 10 '21 at 16:17
  • Which version of g++? Making a template parameter a friend is only legal since C++11, has been illegal before. So if you don't have a sufficiently recent compiler (or don't enable a sufficiently ecent standard, e.g. `-std=c++17`), then it will complain about... – Aconcagua Nov 10 '21 at 16:26
  • @Kevin I must work my search skills better, but yes it answers :). I'm only a bit surprised I haven't found this anywhere else. – Felix.leg Nov 10 '21 at 16:29
  • `friend class T;` is as `void foo(class T);`, it also declare a class (named `T` unrelated to the template parameter) in addition to their usage. – Jarod42 Nov 10 '21 at 16:29

0 Answers0