"Name The Template Parameter" 奇数定义

"Name The Template Parameter" Odd Definition

本文关键字:定义 Template Name The Parameter      更新时间:2023-10-16
template <bool, class t, class u>// why is bool here,class booltype=bool. Are they equivalent?
struct if_
{
    typedef typename t type;
};
template<class t, class u>
struct if_<false,  t,  u>   // what does the <false,t,u> mean?   
{
    typedef typename u type;
};

代码如果来自名为"命名模板参数"的文章。我无法理解这两种结构的定义。

编辑:首先移动了最重要的部分:

if_<true, int, double>::type;  // this is int
if_<false, int, double>::type; // this is double

这方便地定义了一个可以在编译时有条件地定义的类型。

旧答案:

template <bool, class t, class u>// why is bool here,class booltype=bool. Are they equivalent?
struct if_
{
    typedef typename t type;
};

这意味着传递给模板的第一个参数是bool

不等于class booltype=bool.这将是模板的默认typename

template<class t, class u>
struct if_<false,  t,  u>   // what does the <false,t,u> mean?   
{
    typedef typename u type;
};

这是您struct的专业化.如果传递给模板的第一个参数为 false,则将其定义为struct

基本上,假设:

if_<true, int, double> x;
//is defined as
//struct if_
//{
//    typedef int type;
//};

if_<false, int, double> x;
//is defined as
//struct if_
//{
//    typedef double type;
//};

符号基本上告诉 typedef 是什么 - 如果第一个参数是 truetypedef第二个参数,否则第三个参数。

第一个是类型 if_ 的通用模板定义。 bool 是模板参数(模板参数可以是类型或整数值(

第二个是同一模板的部分特化。 专业化意味着您可以设置一些模板参数,但不是全部。

使用

哪一个是这样决定的:如果实际模板参数有专门的,则使用该专用化,否则使用非专用化(本例中的 forst 定义(。 非专用版本充当"默认"选择

>struct if_<false, t, u>是主模板if_的部分专用化,只要模板的第一个参数具有值false,编译器就会实例化,而不管其他两个"类型参数"。您在此处处理的是"非类型"模板参数。此构造的主要目的是根据第一个参数的值选择类型 t 或类型 u,以便

if_<true, int, double>::type

将属于 int

if_<false, int, double>::type

将是类型 double .诚然,如果这是你与 c++ 元编程的"第一次接触",这很难理解,但基本上你会得到一个等效于编译器在编译时计算的传统 if 语句。