473,657 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

typenames in self-referential templates

Hi all,
I've often found myself wanting to write code like the example here.
Since
both MSVC and gcc both reject it, I suspect it is indeed illegal.

gcc: no type named `Name' in `class Collection<Anim al>'
msvc7: error C2039: 'Name' : is not a member of 'Collection<Tra its>'

But to me it seems pretty unambiguous, so I can't see why it's wrong.
Could anybody give me a pointer, either to the standard or the basic
rationale why it's an error?

Thanks

Anthony
template <class T>
class Animal
{
typename T::Name name; // This seems to be an ERROR
};

template <
template <class> class Traits

class Collection :
public Traits < Collection<Trai ts> >
{
public:
typedef char* Name;
};

int main()
{
Collection<Anim al> zoo;
return 0;
}
Jul 19 '05 #1
9 2399
"Anthony Heading" <an*****@magix. com.sg> wrote in message
news:bk******** **@catv02.starc at.ne.jp...
[...]
template <class T>
class Animal
{
typename T::Name name; // This seems to be an ERROR
[...]


Should there be a typedef in there somewhere? I wasn't aware
that 'typename' was allowed to start a declaration.

Dave
Jul 19 '05 #2
David B. Held wrote:
"Anthony Heading" <an*****@magix. com.sg> wrote in message
news:bk******** **@catv02.starc at.ne.jp...
[...]
template <class T>
class Animal
{
typename T::Name name; // This seems to be an ERROR
[...]

Should there be a typedef in there somewhere? I wasn't aware
that 'typename' was allowed to start a declaration.


typename is used as a way to make templates unambiguous.

without typename the code would look like:

T::Name name;

A declaration is

TYPE <DECL> ;

However there is no way for the compiler to know that T::Name is a type.

So "typename T::Name" is a way of indicating that it IS a type.

Jul 19 '05 #3
Anthony Heading wrote:
Hi all,
I've often found myself wanting to write code like the example here.
Since
both MSVC and gcc both reject it, I suspect it is indeed illegal.

gcc: no type named `Name' in `class Collection<Anim al>'
msvc7: error C2039: 'Name' : is not a member of 'Collection<Tra its>'

But to me it seems pretty unambiguous, so I can't see why it's wrong.
Could anybody give me a pointer, either to the standard or the basic
rationale why it's an error?

The code below does not compile.

Try posting the code you really intended to.

template <class T>
class Animal
{
typename T::Name name; // This seems to be an ERROR
};

template <
template <class> class Traits

class Collection :
public Traits < Collection<Trai ts> >
{
public:
typedef char* Name;
};

int main()
{
Collection<Anim al> zoo;
return 0;
}


Jul 19 '05 #4
WW
Gianni Mariani wrote:
Anthony Heading wrote:
Hi all,
I've often found myself wanting to write code like the example
here. Since
both MSVC and gcc both reject it, I suspect it is indeed illegal.

gcc: no type named `Name' in `class Collection<Anim al>'
msvc7: error C2039: 'Name' : is not a member of 'Collection<Tra its>'

But to me it seems pretty unambiguous, so I can't see why it's wrong.
Could anybody give me a pointer, either to the standard or the basic
rationale why it's an error?


The code below does not compile.

Try posting the code you really intended to.


Great God! He posted the code to ask why doesn't it compile!!!

--
WW aka Attila
Jul 19 '05 #5

"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:bk******** @dispatch.conce ntric.net...
David B. Held wrote:
"Anthony Heading" <an*****@magix. com.sg> wrote in message
news:bk******** **@catv02.starc at.ne.jp...
[...]
template <class T>
class Animal
{
typename T::Name name; // This seems to be an ERROR
[...]

Should there be a typedef in there somewhere? I wasn't aware
that 'typename' was allowed to start a declaration.


typename is used as a way to make templates unambiguous.

without typename the code would look like:

T::Name name;

A declaration is

TYPE <DECL> ;

However there is no way for the compiler to know that T::Name is a type.

So "typename T::Name" is a way of indicating that it IS a type.


Also, note that in some contexts, it's not ambiguous
at all what the type is, but the language rules still
demand a 'typename' keyword.

-Mike
Jul 19 '05 #6
"Anthony Heading" <an*****@magix. com.sg> wrote in message news:<bk******* ***@catv02.star cat.ne.jp>...
template <class T>
class Animal
{
typename T::Name name; // This seems to be an ERROR
};

template <
template <class> class Traits
class Collection :
public Traits < Collection<Trai ts> >
{
public:
typedef char* Name;
};


Collection<Anim al> depends on Animal<Collecti on> (via inheritance),
but Animal<Collecti on> depends on Collection<Anim al> (via T::Name).
Can't do that.
int main()
{
Collection<Anim al> zoo;
return 0;
}


Collection's template parameter is called Traits, but Animal isn't a
traits class -- it's the type of element stored in the Collection.
You're actually using Collection as a traits class for Animal, except
that Collection is defined in terms of Animal. Of course, it doesn't
make sense for a contained type to depend on the definition of its
container, anyway.

Perhaps there should be a third class with traits for Animal, such
that Collection< Animal<Traits> > would be used instead. More likely,
Animal should either have a hardcoded Name type, or it should be some
kind of global (or scoped) typedef -- are you really going to use
Animals with different types of Name in your program?

- Shane
Jul 19 '05 #7
"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:bk******** @dispatch.conce ntric.net...
David B. Held wrote:
"Anthony Heading" <an*****@magix. com.sg> wrote in message
news:bk******** **@catv02.starc at.ne.jp...
[...]
template <class T>
class Animal
{
typename T::Name name; // This seems to be an ERROR
[...]

Should there be a typedef in there somewhere? I wasn't aware
that 'typename' was allowed to start a declaration.


typename is used as a way to make templates unambiguous.

without typename the code would look like:

T::Name name;
[...]


Ah. Usually, people typedef dependent names, so I've never seen
typename used in a declaration before.

Dave
Jul 19 '05 #8

"Shane Beasley" <sb******@cs.ui c.edu> wrote in message
news:2f******** *************** ***@posting.goo gle.com...
Collection<Anim al> depends on Animal<Collecti on> (via inheritance),
but Animal<Collecti on> depends on Collection<Anim al> (via T::Name).
Can't do that.
So I infer... but the rationale escapes me. Consider for contrast the code
attached below, which _does_ run fine.
It seems that function names are allowed to have such a circular dependency
in templates, but not types.
Why fundamentally is this OK, but the types are a no-can-do?
Perhaps there should be a third class with traits for Animal, such
that Collection< Animal<Traits> > would be used instead. More likely,
Animal should either have a hardcoded Name type, or it should be some
kind of global (or scoped) typedef -- are you really going to use
Animals with different types of Name in your program?
I am. Obviously this is somewhat of a toy example, but one could imagine
Asian animals whose
Names are wchar_t. Clearly these would have need a Collection zoo of their
own, since the
type signature is different, but yes I could have both in the same program.

With a real program, I have templates mixed into a single class, and I just
find it puzzling
that the _functions_ can happily cross-call each other by passing in the
aggregate class as
a template param to its constituents, but the _types_ cannot be used that
way.

Rgds

Anthony

#include <iostream>

template <class T>
class Animal
{
public:
Animal() {
std::cout << T::something() << std::endl;
}
};

template <
template <class> class Traits

class Collection :
public Traits < Collection<Trai ts> >
{
public:
typedef char* Name;
static Name something() {
return (Name) "Menagerie" ;
}
};

int main()
{
Collection<Anim al> zoo;
return 0;
}


Jul 19 '05 #9
"Anthony Heading" <an*****@magix. com.sg> wrote in message news:<bk******* ***@catv02.star cat.ne.jp>...
Collection<Anim al> depends on Animal<Collecti on> (via inheritance),
but Animal<Collecti on> depends on Collection<Anim al> (via T::Name).
Can't do that.
So I infer... but the rationale escapes me. Consider for contrast the code
attached below, which _does_ run fine.
It seems that function names are allowed to have such a circular dependency
in templates, but not types.
Why fundamentally is this OK, but the types are a no-can-do?


Actually, types are fine, too. What you did differently here was put
the use inside a function. Functions are exempt from this rule because
the compiler can pretend as though they are processed out of line,
whereas it can't generally do the same for declarations in the class.

For instance, this code compiles as well:

template <typename T> struct Animal {
void f () { typedef typename T::Name name; }
};

template <template <class> class T>
struct Collection : T< Collection<T> > {
typedef char *Name;
};

int main () { Collection<Anim al>().f(); }

The reason this works is because the compiler can reinterpret Animal
thus:

template <typename T> struct Animal { void f (); };

template <typename T>
inline void Animal<T>::f () {
typedef typename T::Name name;
}

Note that the mutual dependence between the class definitions is gone
-- the definition of Animal does not use T at all. As a result,
Animal< Collection<Anim al> > and Collection<Anim al> can be fully
processed, and then Animal::f() can work with the result.

Note, also, that this only applies to the bodies of the functions. For
instance, you can't do this:

template <typename T> struct Animal {
void f (typename T::Name *);
};

This reintroduces Animal's dependence on T.
Perhaps there should be a third class with traits for Animal, such
that Collection< Animal<Traits> > would be used instead. More likely,
Animal should either have a hardcoded Name type, or it should be some
kind of global (or scoped) typedef -- are you really going to use
Animals with different types of Name in your program?


I am. Obviously this is somewhat of a toy example, but one could imagine
Asian animals whose
Names are wchar_t. Clearly these would have need a Collection zoo of their
own, since the
type signature is different, but yes I could have both in the same program.


It's hard for me to critique a toy program in a way that applies to
the real program it models, so I'll leave that alone. :)
With a real program, I have templates mixed into a single class, and I just
find it puzzling
that the _functions_ can happily cross-call each other by passing in the
aggregate class as
a template param to its constituents, but the _types_ cannot be used that
way.


Again, the classes' definitions cannot be mutually independent, though
their member functions' definitions can, even when they use dependent
types.

BTW, the tried-and-true way to resolve recursive dependence is to add
a level of abstraction:

template <typename T>
struct Animal { typedef typename T::Name name; };

struct CollectionTrait s { typedef const char *Name; };

template <template <class> class T>
struct Collection : Animal<Collecti onTraits> {
};

- Shane
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4703
by: Marc | last post by:
Hi all, I was using Tkinter.IntVar() to store values from a large list of parts that I pulled from a list. This is the code to initialize the instances: def initVariables(self): self.e = IntVar() for part, list in info.masterList.items():
15
2586
by: Ralf W. Grosse-Kunstleve | last post by:
****************************************************************************** This posting is also available in HTML format: http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html ****************************************************************************** Hi fellow Python coders, I often find myself writing:: class grouping:
1
1879
by: Blace Ice | last post by:
HI, Pls. see the following function declaration: int foo(const char *); How to get the return typename and parameter typenames from the declaration? For example, I need some codes like the following pseudocode: typedef typename ReturnType(&foo)::Type AType; Regards,
18
2265
by: Ralf W. Grosse-Kunstleve | last post by:
My initial proposal (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't exactly get a warm welcome... And Now for Something Completely Different: class autoinit(object): def __init__(self, *args, **keyword_args): self.__dict__.update(
4
2773
by: David Coffin | last post by:
I'd like to subclass int to support list access, treating the integer as if it were a list of bits. Assigning bits to particular indices involves changing the value of the integer itself, but changing 'self' obviously just alters the value of that local variable. Is there some way for me to change the value of the BitSequence object itself? I've also tried wrapping and delegating using __getattr__, but I couldn't figure out how to handle...
4
1809
by: marek.rocki | last post by:
First of all, please don't flame me immediately. I did browse archives and didn't see any solution to my problem. Assume I want to add a method to an object at runtime. Yes, to an object, not a class - because changing a class would have global effects and I want to alter a particular object only. The following approach fails: class kla: x = 1
7
1904
by: Andrew Robert | last post by:
Hi Everyone, I am having a problem with a class and hope you can help. When I try to use the class listed below, I get the statement that self is not defined. test=TriggerMessage(data) var = test.decode(self.qname)
24
2288
by: Peter Maas | last post by:
The Python FAQ 1.4.5 gives 3 reasons for explicit self (condensed version): 1. Instance variables can be easily distinguished from local variables. 2. A method from a particular class can be called as baseclass.methodname(self, <argument list>). 3. No need for declarations to disambiguate assignments to local/instance variables.
84
7179
by: braver | last post by:
Is there any trick to get rid of having to type the annoying, character-eating "self." prefix everywhere in a class? Sometimes I avoid OO just not to deal with its verbosity. In fact, I try to use Ruby anywhere speed is not crucial especially for @ prefix is better- looking than self. But things grow -- is there any metaprogramming tricks or whatnot we can throw on the self? Cheers,
6
1807
by: Bart Kastermans | last post by:
I am playing with some trees. In one of the procedures I wrote for this I am trying to change self to a different tree. A tree here has four members (val/type/left/right). I found that self = SS does not work; I have to write self.val = SS.val and the same for the other members (as shown below). Is there a better way to do this? In the below self is part of a parse tree, F is the parse tree of a function f with argument x. If a node...
0
8413
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7352
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.