【发布时间】:2012-12-06 19:55:59
【问题描述】:
我有一个类似以下的机制,用于为我需要处理的有限数量的不同类型的对象检索某些参数:
template <class T>
struct params {};
template <>
struct params<FooObj>
{
static const int paramA = 17;
static const int paramB = 29;
};
这简化了我以后的代码,因为在我处理不同对象的 switch 语句中,如果我得到一个FooObj,那么我所要做的就是这样:
typedef params<FooObj> paramsT;
然后在该代码 sn-p 中,我可以通过 paramsT::paramC 或其他方式访问参数以使用该 FooObj。
现在我遇到了一个对象,我有这样的东西:
template <>
struct params<BarObj>
{
static const int paramA = 0;
static const int paramB = 9;
static const int paramC = 17;
static const int paramD1 = 18;
static const int paramE1 = 20;
static const int paramD2 = 28;
static const int paramE2 = 30;
static const int paramD3 = 38;
static const int paramE3 = 40;
static const int paramD4 = 48;
static const int paramE4 = 50;
static const int paramD5 = 58;
static const int paramE5 = 60;
static const int paramD6 = 68;
static const int paramE6 = 70;
};
当我处理这个对象时,我开始写如下内容:
typedef params<BarObj> paramsT;
BarObj bar;
//load the first 3 params via the above info into bar
int a,b;
for (int i = 1; i <= 6; ++i)
{
a = doSomethingA(bla + paramsT::paramD1);
b = doSomethingB(bla + paramsT::paramE1);
bla.paramD1 = functionOf(stuff,and,a,b);
}
当然,上面已经硬编码了1,理想情况下它应该是这样的:
typedef params<BarObj> paramsT;
BarObj bar;
//load the first 3 params via the above info into bar
int a,b;
for (int i = 0; i < 6; ++i)
{
a = doSomethingA(bla + paramsT::paramD[i]);
b = doSomethingB(bla + paramsT::paramE[i]);
bla.paramD[i] = functionOf(stuff,and,a,b);
}
虽然对于上面的内容,我需要 params 模板专业化是这样的:
template <>
struct params<BarObj>
{
static const int paramA = 0;
static const int paramB = 9;
static const int paramC = 17;
static const int paramD[] = {18, etc..};
static const int paramE[] = {20, etc..};
};
它不会编译,因为即使硬编码的数组也是非整数类型。是否有一个简单的补丁来解决这个问题,希望看起来与我目前的使用情况不会有太大的不同?或者有办法把那个数组的东西放在那里?
【问题讨论】:
-
为什么要使用模板结构来保存硬编码值而不是简单的值表?
标签: c++ templates static-members