I have a mechanism like the following for retrieving certain parameters for a limited number of different types of objects I need to handle:
template <class T>
struct params {};
template <>
struct params<FooObj>
{
static const int paramA = 17;
static const int paramB = 29;
};
this simplifies my code later because in a switch statement when I handle treating different objects, if I get a FooObj then all I have to do is something like this:
typedef params<FooObj> paramsT;
and then in that code snippet I have access to parameters to work with that FooObj via paramsT::paramC or whatever.
Now I have run into an object where I have something like this:
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;
};
and when I’m handling this object I started writing something like the following:
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);
}
but of course the above has 1 hardcoded into it, and it would ideally read something like this:
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);
}
although for something like the above I would need the params template specialization to be something like this:
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..};
};
which doesn’t compile because the arrays even though hardcoded are non-integral types. Is there an easy patch around this that wouln’t hopefully look too different from my current usage? Or a way to get that array stuff in there?
The “static implicitly inline function static local variable” hack:
note that the resulting values are not “compile time constants” (ie, cannot be used for things like template parameters), but are trivial for compilers to optimize into constants.