struct declaration into another struct

S

slocum

I have a struct like that

struct A {
struct B {
.....
}
...
}

I have to declare previously all that struct and their friends

struct A;
friend struct A;

but how to declare struct B and which is declared into struct A ?

struct A::B; ?
friend struct A::B ?

it doesn't work...
 
L

Looney

I have a struct like that

struct A {
struct B {
.....
}
...

}

I have to declare previously all that struct and their friends

struct A;
friend struct A;

but how to declare struct B and which is declared into struct A ?

struct A::B; ?
friend struct A::B ?

it doesn't work...

You can not just forward declare A::B and make it work
a nested type must be visible before hand so consider doing the
following
class D
{
friend struct A;
};

struct A
{
int m_i;
struct B
{
int m_i;
};
};

class C
{
friend struct A;
friend struct A::B;
};

void somefunc()
{
D d;
C c;
}

make sure A and B are defined in the translation unit,
though usually a class type(class, structor union) does
not need to be declared or defined before a friend declaration
though if it is a class template (say in my eg if C was class template
then)
then A and B must be visible before hand(at least fwd declared).

It seems like the same is required for nested class types as well.

Also watch out for the following things are
 
J

Jim Langston

slocum said:
I have a struct like that

struct A {
struct B {
.....
}
...
}

I have to declare previously all that struct and their friends

struct A;
friend struct A;

but how to declare struct B and which is declared into struct A ?

struct A::B; ?
friend struct A::B ?

it doesn't work...

What doesn't work? The following compiles for me:

struct A
{
friend struct B;
struct B
{
int x;
};
int y;
};

struct C
{
friend struct A::B;
};

int main()
{

}

Does this answer your question?
 
S

slocum

What doesn't work? The following compiles for me:

struct A
{
friend struct B;
struct B
{
int x;
};
int y;

};

struct C
{
friend struct A::B;

};

int main()
{

}

Does this answer your question?

and what if struct A and B are template ? How to declare a friend for
nested template struct ?
template <class> friend struct A::B or what ????
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top