std :: conditional如何工作 [英] How std::conditional works

查看:62
本文介绍了std :: conditional如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个名为 std :: conditional 的元编程小奇迹,描述了这里.在同一参考中,它说可能的实现是

We have this little metaprogramming marvel called std::conditional described here. In the same reference it says that a possible implementation is

template<bool B, class T, class F>
struct conditional { typedef T type; };

template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

所以如果在代码中我做类似的事情

So if in code I do something like

typename std::conditional<true,int,double>::type a;

如果我做类似的事情,编译器将遵循第一个定义

the compiler will follow the first definition and if I do something like

typename std::conditional<false,int,double>::type b

编译器将花费第二个时间.为什么行得通?这里有什么编译规则?

the compiler will take the second. Why does that work ? What compilation rule is in place here ?

推荐答案

简而言之,它与模板专门化规则有关.这些就像函数重载,但用于类型.

In short it has to do with template specialization rules. These are like function overloads but for types.

在这里,编译器更倾向于使用更专业的类型,而不是更通用的类型.

Here compiler prefers a more specialized type to the more general type.

template<bool B, class T, class F>
struct conditional { typedef T type; };

template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

因此,如果编译器看到模板实例化 coditional< false,...> ,则会发现:

So if a template instantiation coditional<false, ...> is seen by compiler it finds:

  • 通用模板 template< bool B,class T,class F>有条件的结构
  • 其所有专长: template< class T,class F>struct conditional< false,T,F>

此时,它尝试匹配尽可能多的专用参数,最终选择 false 来选择专用化.

At that point it tries to match as many specialized arguments as possible and ends up selecting the specialization with false.

例如,引入另一个版本,例如:

For example introducing another version like:

template<class F>
struct conditional<false, int, F> { typedef int type; };

并实例化诸如 conditional< false,int,double> 之类的模板类型将首选专业化

and instantiating a template type like conditional<false, int, double> will prefer specialization

template< class F>struct conditional< false,int,F>

template<类别T,类别F>struct conditional< false,T,F> ,与具有2个专用参数的版本相比,它更为通用.

template<class T, class F> struct conditional<false, T, F> which is more general compared to the version with 2 specialized paramaters.

甚至可以声明最通用的情况(即仅声明但未定义模板的通用形式),并且仅对您真正打算拥有的情况进行专门化处理.所有非专业案例都将导致编译错误,并要求用户针对特定类型对案例进行专业化处理.

It is even OK to just declare the most generic case (i.e. generic form of the template is just declared but not defined) and only have specializations for cases you really intend to have. All non-specialized cases will result in compile errors and asking the user to specialize the case for a particular type.

这篇关于std :: conditional如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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