Preprocessor magic to expand template instantiation (2)

M

mathieu

Let's try again,

Hi there,

I am looking for a trick to avoid maintaining the 'Create' function
as describe below. All it does is a simple template instantiation, are
there any trick which would avoid having to maintain this 'Create' as
the number of enum grows ?

Thanks

#include <string.h>

typedef enum {
TYPE1,
TYPE2
} TYPES;

class type1 {};
class type2 {};

template <int T> struct Factory;
template <> struct Factory<TYPE1> { typedef type1 Type; };
template <> struct Factory<TYPE2> { typedef type2 Type; };

template <int N>
typename Factory<N>::Type* Create()
{
return new typename Factory<N>::Type;
}

int main()
{
const char *file[] = {
"TYPE2",
"TYPE1",
};
const unsigned int n = sizeof(file) / sizeof(*file);
for(unsigned int i = 0; i < n; ++i)
{
if( strcmp(file, "TYPE1" ) == 0 )
{
type1 *t = Create<TYPE1>();
}
else if( strcmp(file, "TYPE2" ) == 0 )
{
type2 *t = Create<TYPE2>();
}
}
return 0;
}
 
M

mathieu

Let's try again,

Hi there,

  I am looking for a trick to avoid maintaining the 'Create' function
as describe below. All it does is a simple template instantiation, are
there any trick which would avoid having to maintain this 'Create' as
the number of enum grows ?

Thanks

#include <string.h>

typedef enum {
  TYPE1,
  TYPE2

} TYPES;

class type1 {};
class type2 {};

template <int T> struct Factory;
template <> struct Factory<TYPE1> { typedef type1 Type; };
template <> struct Factory<TYPE2> { typedef type2 Type; };

template <int N>
typename Factory<N>::Type* Create()
{
   return new typename Factory<N>::Type;

}

int main()
{
  const char *file[] = {
    "TYPE2",
    "TYPE1",
  };
  const unsigned int n = sizeof(file) / sizeof(*file);
  for(unsigned int i = 0; i < n; ++i)
    {
    if( strcmp(file, "TYPE1" ) == 0 )
      {
      type1 *t = Create<TYPE1>();
      }
    else if( strcmp(file, "TYPE2" ) == 0 )
      {
      type2 *t = Create<TYPE2>();
      }
    }
  return 0;

}


I just found out: BOOST_PP_LIST_FOR_EACH which looks pretty cool.

http://www.boost.org/doc/libs/1_39_0/libs/preprocessor/doc/examples/catch_builtin.cpp

Thx
 

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

Staff online

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top