繁体   English   中英

使用std :: conditional根据模板参数选择成员类型

[英]using std::conditional to choose member type based on template parameter

这是我的程序,尝试使用std :: conditional基于整数模板参数的值设置成员变量的类型。

#include <stdio.h>
#include <type_traits>
using namespace std;

class cool{
public:
  cool(){ printf("Cool!\n");  }
};

class notcool{
public:
  notcool(){ printf("Not cool!\n");  }
};

template<int N>
class myclass{
public:
  typedef std::conditional<N==5,cool,notcool> thetype;
  thetype theinst;
};

int main(){
  printf("Testing\n");
  myclass<5> myc5;
  myclass<6> myc6;
  printf("Done testing\n");
  return 0; 
} 

我希望我的程序提供以下输出:

测试中

凉!

不酷!

完成测试

相反,输出是

测试中

完成测试

我的编译器是GCC 4.9,而我编译该程序的方式是使用命令g ++ test -std = c ++ 11 -o test

谁能告诉我为什么该程序没有提供我期望的输出?

typedef typename std::conditional<N==5,cool,notcool>::type thetype;
//      ^^^^^^^^                                    ^^^^^^

thetype实际上是不cool ,也没有notcool 但是std::conditional

是。 std::conditional是一种类型,这就是大多数类型特征实现的方式。 如果要从条件中获取基础类型,则需要从std::conditional访问基础type成员。 这也是大多数类型特征的实现方式:它们都具有type成员,可用于访问所需的实际类型,而不是类型特征类型。

在C ++ 14中,您将使用std::conditional_t ,它只是std::conditional type成员的别名,但是由于您使用的是C ++ 11,因此需要显式访问它:

typedef typename std::conditional<N == 5, cool, notcool>::type thetype;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM