C++ 如何使用类的属性作为模板参数/进行专业化?
下面的例子应该说明我的问题:如果我有一个类作为模板参数,我如何使用该类的(常量)属性C++ 如何使用类的属性作为模板参数/进行专业化?,c++,templates,C++,Templates,下面的例子应该说明我的问题:如果我有一个类作为模板参数,我如何使用该类的(常量)属性 直接,如标有(1)的行所示。据我所知,, 这应该行得通。这是“正确”的方式吗 作为模板专业化的参数。所以我想专门指定一个容器用于固定,另一个容器用于非固定。在这里,我不知道 代码示例: class IdxTypeA{ const bool fixed = true; const int LEN = 5; // len is fixed on compile time } class IdxTypeB{
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>{
...
}
class-IdxTypeA{
const bool fixed=真;
const int LEN=5;//LEN在编译时是固定的
}
类IDX类型B{
const bool fixed=false;
int len;//可以在运行时设置len
}
类IdxTypeC{
const bool fixed=false;
int len;//可以在运行时设置len
}
模板类容器{}
模板
类容器{
int值[IDX.LEN];//**(1)*****
}
模板
类容器{
...
}
(问题不在于容器,它只是一个粗略的例子。)首先,您需要将编译时属性转换为实际的常量表达式,方法是使它们成为静态的:
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>
{
};
模板类容器;
模板
类容器
{
int值[IDX::LEN];
};
模板
类容器
{
};
我稍微澄清了这个问题:可能我还有IdxTypeC、IdxTypeD等等,它们可以是固定的,也可以是不固定的。所有这些都应该触发正确的专业化。所以我不想专门针对某个类型,而是针对其中的某个属性。