about struct keyword

L

lp-boy

Hello!

Is the following code legal?

template<class T>
struct holder{};

struct A
{
holder<struct B*> h; //!!!
//but holder<B*> h; error: B was not declared
};

int main()
{
A a;
}

If yes, why? Thanks in advance.
 
N

Niklas Norrthon

Hello!

Is the following code legal?

template<class T>
struct holder{};

struct A
{
holder<struct B*> h; //!!!
//but holder<B*> h; error: B was not declared
};

int main()
{
A a;
}

If yes, why? Thanks in advance.

In order to use a type, its size must be known. In case of pointers a
forward declaration is all that is needed, since pointer size does not
depend on the internals of the type. All pointers to user defined types
have the same size.

In your code you say holder<struct B*> h;
The struct word makes this a forward declaration for B at the latest
possible moment.
When you just say holder<B*> B isn't declared yet, so it can't be used.

/Niklas Norrthon
 
M

Marcus Kwok

Hello!

Is the following code legal?

template<class T>
struct holder{};

struct A
{
holder<struct B*> h; //!!!
//but holder<B*> h; error: B was not declared
};

int main()
{
A a;
}

If yes, why? Thanks in advance.

The way I interpret it, the line

holder<struct B*> h;

is equivalent to forward-declaring B as a struct.


template <class T>
struct holder { };

struct B;

struct A {
holder<B*> h;
};

int main()
{
A a;
}


works for me (VS .NET 2003).
 
G

Greg

Marcus said:
The way I interpret it, the line

holder<struct B*> h;

is equivalent to forward-declaring B as a struct.


template <class T>
struct holder { };

struct B;

struct A {
holder<B*> h;
};

int main()
{
A a;
}

The two programs are similar but not the same. The struct B declaration
appears first within struct "A" therefore it is a forward declaration
for an inner struct of A, named B (or ::A::B fully qualified). Of
course there are no inner structs defined in struct A, let alone one
named B.

But no matter, since the holder class template is being instantiated
with a pointer to B, the fact that there is no such type is not an
error.

Greg
 
M

Marcus Kwok

Greg said:
The two programs are similar but not the same. The struct B declaration
appears first within struct "A" therefore it is a forward declaration
for an inner struct of A, named B (or ::A::B fully qualified). Of
course there are no inner structs defined in struct A, let alone one
named B.

OK, then what I really meant <g> was:

template <class T>
struct holder { };

struct A {
struct B;
holder<B*> h;
};

int main()
{
A a;
}
 

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