Problem with creating list of types in C ++ 98 without macros
So, I am reading this article from Andrei Alexandrescu on how to create type lists, but the following code from the article does not compile with MSVC / GCC:
template <class H, class T>
struct typelist
{
typedef H head;
typedef T tail;
};
class null_typelist {};
template <class T1>
struct cons<T1, null_typelist, null_typelist,
null_typelist>
{
typedef typelist<T1, null_typelist> type;
};
template <class T1, class T2>
struct cons<T1, T2, null_typelist, null_typelist>
{
typedef typelist<T1, typelist<T2,
null_typelist> > type;
};
template <class T1, class T2, class T3>
struct cons<T1, T2, T3, null_typelist>
{
typedef typelist<T1, typelist<T2, typelist<T3,
null_typelist> > > type;
};
template <class T1, class T2, class T3, class T4>
struct cons
{
typedef typelist<T1, typelist<T2, typelist<T3,
typelist<T4, null_typelist> > > > type;
};
typedef cons<float, double, long double>::type
floating_point_types;
I am getting the following errors:
a.cpp:21:8: error: 'cons' is not a class template
struct cons<T1, null_typelist, null_typelist,
^~~~
a.cpp:28:49: error: wrong number of template arguments (4, should be 1)
struct cons<T1, T2, null_typelist, null_typelist>
^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
null_typelist>
^
a.cpp:35:38: error: wrong number of template arguments (4, should be 1)
struct cons<T1, T2, T3, null_typelist>
^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
null_typelist>
^
a.cpp:42:8: error: redeclared with 4 template parameters
struct cons
^~~~
a.cpp:22:18: note: previous declaration 'template<class T1> struct cons' used 1
template parameter
null_typelist>
^
a.cpp:48:40: error: wrong number of template arguments (3, should be 1)
typedef cons<float, double, long double>::type
^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
null_typelist>
^
a.cpp:49:5: error: expected initializer before 'floating_point_types'
floating_point_types;
^~~~~~~~~~~~~~~~~~~~
I need this in C ++ 98 for a library I am writing and something more like variadic templates or third party such as boost::mpl
is not an option.
So what's the problem? I don't really like template metaprogramming (yet) ...
source to share
I don't know if I can work in msvc (but work with my g ++), but in your code, you are declaring partial specializations cons
.
So before the first partial specialization (off topic: I suggest using typename
instead class
for template parameters)
template <typename T1>
struct cons<T1, null_typelist, null_typelist,
null_typelist>
{
typedef typelist<T1, null_typelist> type;
};
you should insert a generic declaration which I suppose could be like
template <typename,
typename = null_typelist,
typename = null_typelist,
typename = null_typelist>
struct cons;
source to share