Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template macro shortcut

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?

like image 758
Corey Avatar asked Oct 07 '09 20:10

Corey


People also ask

How do I assign a shortcut to a macro in Excel?

Right-click a blank area of the ribbon. Choose “Customize Quick Access Toolbar.” From the dialog box that appears, choose “Macros” for “Choose commands from:” and select your macro from the list. Click “Add >>” and “Save.”

Can you make templates in C?

C does not have static templates, but you can use macros to emulate them.


1 Answers

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>
...
like image 68
Mark Ransom Avatar answered Oct 27 '22 08:10

Mark Ransom