C ++类型特征 [英] C++ Type Traits

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

问题描述

我了解它们对有关您实例化它们的类型的信息进行编码,但是它们如何工作?比如说类型特征std::is_class.它是如何工作的?所有实现似乎都是空的结构,我得承认我在挠头.

I understand they encode information about the type you instantiate them with, but how do they work? Say, for instance, the type trait std::is_class. How does it do its work? All implementations seem like empty structs, and I gotta admit I'm scratching my head.

名称似乎足够描述性,因此我可以理解它们的含义,但是使用类型特征的典型情况是什么?

The names seem descriptive enough, so I can understand what they mean, but what are typical scenarios that make use of type traits?

我找不到有关该主题的介绍性资源(或有关SO的问题).指针将不胜感激.

I cannot find introductory resources on the subject (or questions on SO). Pointers would be appreciated.

推荐答案

某些类型特征,例如std::is_class,仅使用编译器内部函数(也称为内置函数).没有编译器的特殊支持,您将无法自己编写这些代码.

Some type traits, like std::is_class just use compiler intrinsics (aka built-ins). You cannot write these yourself without special support from the compiler.

类型特征在通用上下文中最有用-您可能希望根据类型的属性来专门化事物,或对模板参数施加限制.例如,当迭代器是指向POD的指针时,std::copy的实现可以在内部使用std::memcpy而不是显式循环.这可以通过SFINAE来实现.

Type traits are mostly useful in generic context—you may want to specialize things based on the properties of types, or impose restrictions on template arguments. For example, an implementation of std::copy may use std::memcpy internally instead of an explicit loop when the iterators are pointers to PODs. This can be achieved with SFINAE.

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

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