“命名模板参数”奇数定义

时间:2012-04-03 16:36:09

标签: c++

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;
};

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

3 个答案:

答案 0 :(得分:4)

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

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是第二个参数,否则是第三个参数。

答案 1 :(得分:0)

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

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

使用哪一个是这样决定的:如果实际模板参数存在明确的特化,则使用该特化,否则使用非专用(本例中为forst定义)。非专业版本作为“默认”选择

答案 2 :(得分:0)

struct if_<false, t, u>是主模板if_的部分特殊化,只要模板的第一个参数的值为false,编译器就会对其进行实例化,而不管其他两个“类型” α参数”。您在这里处理“非类型”模板参数。此构造的主要目的是选择类型t或类型u,具体取决于第一个参数的值,以便

if_<true, int, double>::type

的类型为int

if_<false, int, double>::type

的类型为double。不可否认,如果它是你与c ++元编程的“第一次接触”,那么基本上你得到了编译器在编译时评估的传统if语句的等价物。

相关问题