下面的例子应该可以说明我的问题:如果我有一个类作为模板参数,我如何使用该类的(常量)属性...
直接,如标有 (1) 的行所示。据我所知, 这应该工作。这是“正确”的方式吗?
作为模板特化的参数。因此,我想将其中一个 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/