【问题标题】:std::enable_if second askstd::enable_if 第二次询问
【发布时间】:2012-11-08 04:50:44
【问题描述】:

我对 std::enable_if 很陌生,想知道如何使用它。 我有一个模板类:

template<int a, int b>
class foo {
  int c;
}

我只希望模板在何时有成员 c

a = 5. 

如何使用 std::enable_if 做到这一点? 这是使用 std::enable_if 的正确案例吗?

【问题讨论】:

  • 这与您的first question 有何不同?也就是说,您为什么不能在此示例中也使用接受的答案中建议的技术?
  • 第一个是关于强制 a+b 遵循一些规则。这是关于根据一些关于 a 的规则来包含 c 的

标签: c++ std enable-if


【解决方案1】:

您可以使用部分专业化。不需要std::enable_if

//primary template
template<int a, int b>
class foo 
{
      //whatever 
};

//partial specialization
template<int b>
class foo<5,b>  //when a = 5, this specialization will be used!
{
  int c;  //it has member c
};

用法:

foo<1,3>  f1; //primary template is used
foo<5,3>  f2; //partial specialization is used

【讨论】:

  • @WhatABeautifulWorld:那就好好提问吧。在问题中提供更多信息。另外,如果有帮助,您可以尝试使用基本公共类模板。
猜你喜欢
  • 1970-01-01
  • 2013-09-29
  • 2012-10-26
  • 2014-08-29
  • 2013-06-03
  • 2016-02-25
  • 1970-01-01
  • 2014-12-12
  • 2021-03-07
相关资源
最近更新 更多