C ++中的空类的优点 [英] Advantages of an empty class in C++

查看:178
本文介绍了C ++中的空类的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个空类的可能的优点/用途是什么?



PS:
这个问题可能听起来很小,只是为了学习目的而没有实际意义。 FYI googling没有帮助。

解决方案

一个用途是在模板(meta-)编程中:例如迭代器标记实现为空类。这里唯一的目的是在编译时传递信息,所以你可以检查,如果一个迭代器传递给例如。



这是

>真正的简化,只是想一个想法。这里的标签类的目的是决定,一个算法的实现使用:

  class forward_iterator_tag {}; 
class random_access_iterator_tag {};

class MySimpleForwardIterator {
public:
typedef typename forward_iterator_tag tag;
// ...
};

class MySimpleRandomIterator {
public:
typedef typename random_access_iterator_tag tag;
// ...
};

template< class iterator,class tag>
void myfunc_int(iterator it,tag t){
//一般实现myfunc
}

template< class iterator>
void myfunc_int< iterator,forward_iterator_tag>(iterator it){
//正向迭代器的实现
}

template< class iterator>
void myfunc_int< iterator,random_access_iterator_tag>(iterator it){
//随机访问迭代器的实现
}

template< class iterator>
void myfunc(iterator it){
myfunc_int< iterator,typename iterator :: tag>(it);
}

(我希望我有这个权利, ...)



使用此代码,您可以在任意迭代器上调用 myfunc 正确的实现取决于迭代器类型(即tag)。


What could be the possible advantages/uses of having an empty class?

P.S: This question might sound trivial to some of you but it is just for learning purpose and has no practical significance. FYI googling didn't help.

解决方案

One use would be in template (meta-)programming: for instance, iterator tags are implemented as empty classes. The only purpose here is to pass around information at compilation time so you can check, if an iterator passed to e.g. a template function meets specific requirements.

EXAMPLE:

This is really simplified, just to ge an idea. Here the purpose of the tag class is to decide, which implementation of an algorithm to use:

class forward_iterator_tag {};
class random_access_iterator_tag {};

class MySimpleForwardIterator {
public:
  typedef typename forward_iterator_tag tag;
  // ...
};

class MySimpleRandomIterator {
public:
  typedef typename random_access_iterator_tag tag;
  // ...
};

template<class iterator, class tag>
void myfunc_int(iterator it, tag t) {
  // general implementation of myfunc
}

template<class iterator>
void myfunc_int<iterator, forward_iterator_tag>(iterator it) {
  // Implementation for forward iterators
}

template<class iterator>
void myfunc_int<iterator, random_access_iterator_tag>(iterator it) {
  // Implementation for random access iterators
}

template<class iterator>
void myfunc(iterator it) {
  myfunc_int<iterator, typename iterator::tag>(it);
}

(I hope I got this right, it's been a while since I used this ...)

With this code, you can call myfunc on an arbitrary iterator, and let the compiler choose the correct implementation depending on the iterator type (i.e. tag).

这篇关于C ++中的空类的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆