特征类如何工作,它们是做什么的? [英] How do traits classes work and what do they do?

查看:45
本文介绍了特征类如何工作,它们是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Scott Meyers的 有效的C ++ 。他在谈论特质类,我知道在编译期间需要它们来确定对象的类型,但是我无法理解他对这些类实际作用的解释? (从技术角度来看)

I'm reading Scott Meyers' Effective C++. He is talking about traits classes, I understood that I need them to determine the type of the object during compilation time, but I can't understand his explanation about what these classes actually do? (from technical point of view)

推荐答案

也许您期望某种可以使类型特征起作用的魔术。在这种情况下,请失望-没有魔法。类型特征是为每种类型手动定义的。例如,考虑 iterator_traits ,它为迭代器提供typedef(例如 value_type )。

Perhaps you’re expecting some kind of magic that makes type traits work. In that case, be disappointed – there is no magic. Type traits are manually defined for each type. For example, consider iterator_traits, which provides typedefs (e.g. value_type) for iterators.

使用它们,您可以编写

iterator_traits<vector<int>::iterator>::value_type x;
iterator_traits<int*>::value_type y;
// `x` and `y` have type int.

但是要使这项工作有效,实际上其中有一个显式定义 < iterator> 标头,其内容如下:

But to make this work, there is actually an explicit definition somewhere in the <iterator> header, which reads something like this:

template <typename T>
struct iterator_traits<T*> {
    typedef T value_type;
    // …
};

这是 iterator_traits的部分专业化 类型用于类型为 T * 的类型,即某种通用类型的指针。

This is a partial specialization of the iterator_traits type for types of the form T*, i.e. pointers of some generic type.

同样, iterator_traits 专用于其他迭代器,例如 typename vector< T> :: iterator

In the same vein, iterator_traits are specialized for other iterators, e.g. typename vector<T>::iterator.

这篇关于特征类如何工作,它们是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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