Re: How to create an array of data types only
From: John Harrison (john_andronicus_at_hotmail.com)
Date: 05/13/04
- Next message: Frederic Banaszak: "Re: Creating an Icon For my App"
- Previous message: Alf P. Steinbach: "Re: C++ Exercises"
- In reply to: billy: "How to create an array of data types only"
- Next in thread: John Harrison: "Re: How to create an array of data types only"
- Reply: John Harrison: "Re: How to create an array of data types only"
- Reply: Siemel Naran: "Re: How to create an array of data types only"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 13 May 2004 06:50:59 +0100
"billy" <billy_dev#@#cox#.#net> wrote in message
news:zDDoc.4148$2c7.587@fed1read07...
> I've got a set of subclasses that each derive from a common base class.
What
> I'd
> like to do is create a global array of the class types (or, class names)
> that a manager
> class can walk through in its constructor and instantiate one of each of
the
> class types
> in this global array. So, it's almost like the global array has to hold
data
> types as
> opposed to data.
You cannot create an array of types, but you can create a list of types.
Here's some code to illustrate the idea.
In the code below MyTypeList is the list of types and I recursively loop
through it using the print_type_names template function.
#include <iostream>
using namespace std;
template <class T, class U>
struct TypeList
{
typedef T Head;
typedef U Tail;
};
struct NullType
{
};
#define TYPELIST_0() NullType
#define TYPELIST_1(A) TypeList<A, TYPELIST_0() >
#define TYPELIST_2(A, B) TypeList<A, TYPELIST_1(B) >
#define TYPELIST_3(A, B, C) TypeList<A, TYPELIST_2(B, C) >
#define TYPELIST_4(A, B, C, D) TypeList<A, TYPELIST_3(B, C, D) >
#define TYPELIST_5(A, B, C, D, E) TypeList<A, TYPELIST_4(B, C, D, E) >
struct SomeType {};
struct AnotherType {};
struct YetAnotherType {};
typedef TYPELIST_5(int, SomeType, double, AnotherType, YetAnotherType)
MyTypeList;
template <class TL>
void print_type_names()
{
cout << typeid(TL::Head).name() << '\n';
print_type_names<TL::Tail>();
}
template <>
void print_type_names<NullType>()
{
}
int main()
{
print_type_names<MyTypeList>();
}
On my computer this prints
int
SomeType
double
AnotherType
YetAnotherType
yours may differ because the output of typeid(...).name() is implementation
dependent.
This type list idea was popularised by Alexei Alexandrescu in his book
Modern C++ Design, if you are interested.
john
- Next message: Frederic Banaszak: "Re: Creating an Icon For my App"
- Previous message: Alf P. Steinbach: "Re: C++ Exercises"
- In reply to: billy: "How to create an array of data types only"
- Next in thread: John Harrison: "Re: How to create an array of data types only"
- Reply: John Harrison: "Re: How to create an array of data types only"
- Reply: Siemel Naran: "Re: How to create an array of data types only"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|