"Name The Template Parameter" 奇数定义
"Name The Template Parameter" Odd Definition
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 是什么 - 如果第一个参数是 true
,typedef
第二个参数,否则第三个参数。
第一个是类型 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
语句。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 表示"accepting anything for this template argument" C++概念的通配符
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- Template类定义中的Template方法与声明不匹配
- "template<class C> void mini(C &a4, C b4) { a4 = min(a4, b4); }"定义的含义是什么?
- 重新定义类<template-parameter-1-2>的默认参数
- 定义模板类,但获取'is not a class template'
- 是否可以定义"template function pointer"的类型?
- 更改专用化"template<...>"行中模板参数的顺序是否会导致定义重复或歧义?
- "Name The Template Parameter" 奇数定义
- 从Template模板参数中定义并推导参数
- 为template类定义numeric_limits-max函数
- 在类模板定义中使用template-name代替template-id
- 使用"A:<int>:template B x;"定义变量是否C++符合标准<int>?
- 在C++中的Template中定义类的新对象,错误:缺少Template参数
- 在private类中定义Template