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

ttb*_*ttb 3 c++ templates type-traits c++11

这是我的程序,它尝试使用 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; 
} 
Run Code Online (Sandbox Code Playgroud)

我希望我的程序给出以下输出:

测试

凉爽的!

不酷!

完成测试

相反,输出是

测试

完成测试

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

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

T.C*_*.C. 6

typedef typename std::conditional<N==5,cool,notcool>::type thetype;
//      ^^^^^^^^                                    ^^^^^^
Run Code Online (Sandbox Code Playgroud)

  • @HolyBlackCat `使用类型 = std::conditional_t&lt;...&gt;;` (3认同)

Rak*_*111 6

thetype其实不是cool,也不是notcool。但是std::conditional

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

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

typedef typename std::conditional<N == 5, cool, notcool>::type thetype;
Run Code Online (Sandbox Code Playgroud)