【问题标题】:using std::conditional to choose member type based on template parameter使用 std::conditional 根据模板参数选择成员类型
【发布时间】:2017-07-08 17:18:24
【问题描述】:

这是我的程序,它尝试使用 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

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

【问题讨论】:

  • 这些是构造函数,应该在实例化对象 myclass 时自动调用。

标签: c++ c++11 templates typetraits


【解决方案1】:
typedef typename std::conditional<N==5,cool,notcool>::type thetype;
//      ^^^^^^^^                                    ^^^^^^

【讨论】:

  • 谢谢,这确实有效。你能解释一下这和我的代码中的那行有什么区别吗?
  • 较短的 C++14 方式:typedef std::conditional_t&lt;...&gt; thetype;.
  • @HolyBlackCat using thetype = std::conditional_t&lt;...&gt;;
【解决方案2】:

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;

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 2012-12-31
    • 2020-02-27
    • 1970-01-01
    • 2014-07-26
    • 2016-05-31
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多