Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Tiny friend-problem

45 views
Skip to first unread message

Bonita Montero

unread,
Apr 1, 2019, 4:49:04 PM4/1/19
to
I've got a seemingly simple problem with two instantiations of the
same template-class which must be friends of each other. Here's the
example-code:

template<typename T>
class C
{
public:
template<typename U>
void f123( C<U> &other )
{
other.i = 1;
}

private:
// doesn't work
// template<typename U>
// friend class C<U>;

int i;
};

int main()
{
C<int> ci;
C<float> cf;

ci.f123( cf );
}

Bonita Montero

unread,
Apr 2, 2019, 2:12:33 AM4/2/19
to
Just asked the same question on Stack Overflow.

This...>     // doesn't work>     // template<typename U>>     //
friend class C<U>;... should be this ...
template<typename U>
friend class C;

Thiago Adams

unread,
Apr 2, 2019, 1:50:15 PM4/2/19
to
Maybe this can help
http://www.gotw.ca/gotw/076.htm

Each template class is a unique type with no relationship
with the other instantiations. You are trying to declare
a friend that you know known anything about it.

In case you have a class for numeric types you can make
your class explicitly be friend of each possible
instantiations that you can think about. (int, long, double etc...)


template<typename T>
class C
{
public:
template<typename U>
void f123( C<U> &other )
{
other.i = 1;
}

private:

friend class C<float>;
friend class C<int>;

...etc...

int i;
};



Daniel

unread,
Apr 2, 2019, 2:10:29 PM4/2/19
to
On Tuesday, April 2, 2019 at 1:50:15 PM UTC-4, Thiago Adams wrote:
>
> Maybe this can help
> http://www.gotw.ca/gotw/076.htm
>
That's old :-) Things have changed.

Bonita's second post has the correct answer.

Daniel

Thiago Adams

unread,
Apr 2, 2019, 2:38:32 PM4/2/19
to
On Tuesday, April 2, 2019 at 3:10:29 PM UTC-3, Daniel wrote:
> On Tuesday, April 2, 2019 at 1:50:15 PM UTC-4, Thiago Adams wrote:
> >
> > Maybe this can help
> > http://www.gotw.ca/gotw/076.htm
> >
> That's old :-) Things have changed.
>
I missed the answer because of formatting.
Sorry for the noise.

I didn't know about that.
Interesting that any instantiation of C
is friend.
0 new messages