C ++模板宏快捷方式 [英] C++ template macro shortcut
本文介绍了C ++模板宏快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用模板时,通常会得到类似以下内容的信息:
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;
所以我的课程变成了:
#include "template_types.h"
template <typename T>
class the_class
{
public:
TEMPLATE_TYPES(T)
...
};
这看起来更干净,并且在制作其他模板类时避免重复.这是一件好事吗?还是应该避免这种情况,而只复制粘贴typedef?
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?
推荐答案
当然,您正在做的事情行得通,但这有点老套.您是否尝试过将这些东西放到您可以派生的另一个模板类中?
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>
...
这篇关于C ++模板宏快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文