c++ - 如何使用类的属性作为模板参数/进行特化?

标签 c++ templates

下面的例子应该可以说明我的问题:如果我有一个类作为模板参数,我如何使用该类的(常量)属性...

  1. 直接,如标有 (1) 的行所示。据我所知, 这应该工作。这是“正确”的方式吗?

  2. 作为模板特化的参数。因此,我想将其中一个 Container 专门化为 fixed,另一个专门化为 not fixed。在这里,我不知道。

代码示例:

class IdxTypeA{
  const bool fixed = true;
  const int LEN = 5; // len is fixed on compile time
}

class IdxTypeB{
  const bool fixed = false;
  int len; // len can be set on runtime
}

class IdxTypeC{
  const bool fixed = false;
  int len; // len can be set on runtime
}

template<class IDX> class Container { }

template<>
class Container<here comes the specialisation for fixed len>{
  int values[IDX.LEN]; // **** (1) *****
}

template<>
class Container<here comes the specialisation for not fixed length>{
  ... 
}

(问题与容器无关,只是粗略的示例。)

最佳答案

首先,您需要通过将编译时属性设为static 将它们转换为实际的常量表达式:

class IdxTypeA {
  static const bool fixed = true;
  static const int LEN = 5; // len is fixed on compile time
}

有了这个,你可以(部分地)专注于这些就好了,像这样:

template<class IDX, bool IS_FIXED = IDX::fixed> class Container;

template <class IDX>
class Container<IDX, true>
{
  int values[IDX::LEN];
};

template <class IDX>
class Container<IDX, false>
{
};

关于c++ - 如何使用类的属性作为模板参数/进行特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27235488/

相关文章:

c++ - 模板类给出链接器错误

c++ - 提供适当的 operator<< 和可变模板特化

c++ - DropDownList 控件右键单击事件

c++ - QextSerialPort 的字符编码问题 (Qt/C++)

c++ - 调用模板函数的误报错误 503

c++ - 为什么派生类不能代替基类作为模板参数?

c++ - 如何访问一片 packed_bits<> 作为 std::bitset<>?

c++ - 为什么 std::unique_ptr 比标准指针慢得多……在优化之前?

c++ - 一个模板化的 'strdup()' ?

c++ - 地址分配给整型变量