C++ template macro shortcut

2020-07-06 07:14发布

问题:

Often when working with templates, you end up with something like:

template <T>
class the_class
{
public:
   // types
   typedef T value_type;
   typedef const value_type const_value_type;

   typedef value_type& reference;
   typedef const_value_type& const_reference;

   typedef value_type* pointer;
   typedef const_value_type* const_pointer;

   ...
};

This is lot's of the same stuff, though, copied to lots of different templated classes. Is it worthwhile to create something like:

// template_types.h

#define TEMPLATE_TYPES(T) \
       typedef T value_type; \
       typedef const value_type const_value_type; \
       typedef value_type& reference; \
       typedef const_value_type& const_reference; \
       typedef value_type* pointer; \
       typedef const_value_type* const_pointer;

So my class just becomes:

#include "template_types.h"

template <typename T>
class the_class
{
public:
   TEMPLATE_TYPES(T)
   ...
};

This seems cleaner, and avoids duplication when I make other template classes. Is this a good thing? Or should I avoid this and just copy-paste typedefs?

回答1:

Sure, what you're doing would work, but it's kind of old-school. Have you tried to put that stuff into another template class that you could derive from?

template <typename T>
class template_defs
{
public:
   // types
   typedef T value_type;
   typedef const value_type const_value_type;
   typedef value_type& reference;
   typedef const_value_type& const_reference;
   typedef value_type* pointer;
   typedef const_value_type* const_pointer;
};

template <typename T>
class the_class : public template_defs<T>
...