Re: case/switch metaprogramming
"Aaron Graham" <atgraham@gmail.com> wrote in message
news:1185319852.842812.146190@z24g2000prh.googlegroups.com...
Very nice. One improvement on that: I can get the same effect without
the special "default" case in the generalized version of the function:
template<unsigned hi_id>
Dev* getDeviceFrom(unsigned dev_id) {
if (dev_id == hi_id)
return new Device<hi_id>; // Bingo!
return getDeviceFrom<hi_id-1>(dev_id);
}
template<>
Dev* getDeviceFrom<0>(unsigned i) {
return new Device<0>(); // default case here
}
That should generate less code.
Now I'm trying to figure out a way to get it to "skip over" devices
that aren't defined, to fall back on the default case. For instance,
if Device<12> isn't defined, I want a Device<0>, but this
implementation will give me a compile time error instead.
Essentially, I need the compiler to elide the "if" clause for
getDeviceFrom<12> when it finds that type is not declared.
It seems to me there are at least two (quick and dirty) ways to do that, but
both of them require something extra (this is untested):
1) Add an if clause for the special case:
template<unsigned hi_id>
Dev* getDeviceFrom(unsigned dev_id) {
if (dev_id == hi_id)
return new Device<hi_id>; // Bingo!
if (dev_id == 12)
return new Device<0>; // Device<12> not defined, use default
return getDeviceFrom<hi_id-1>(dev_id);
}
or 2) add a new template function for the special case:
template<>
Dev* getDeviceFrom<12>(unsigned i) {
return new Device<0>(); // Device<12> not defined, use default
}
There are probably much more elegant ways, but these were the most obvious.
- Dennis
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]