Re: template problem: local variable as non-type argument
On 5 ??????, 11:34, "vl106" <vl...@hotmail.com> wrote:
Base& Factory::createInstance(int i) {
// PROBLEM:
// error C2971: 'C' : template parameter 'T' : 'i' : a local variable
cannot be used as
// a non-type argument
// WORKS: int const val = 0;
return C<i>(); //ignore warning: returning address of local variable or
temporary
}
Option 1, "switch" statement is much faster than "if" one:
Base& Factory::createInstance(int i) {
switch(i){
case 1: return C<1>();
case 2: return C<2>();
...
}
}
Option 2, linear recursive helper function:
const int max_n = 100;
template<int n>
struct helper
{
static Base& func(int i)
{
return i == n? C<n>() : helper<n+1>::func(i);
}
};
template<>
struct helper<max_n>
{
static Base& func(int i)
{
return C<max_n>();
}
};
Base& Factory::createInstance(int i) {
return helper<0>(i);
}
Option 3, similar to Option 1 but using Boost.Preprocessor library you
can avoid manual array completion and functions writing:
// the following functions can be generated by Boost.Preprocessor
(http://www.boost.org/doc/libs/1_37_0/libs/preprocessor/doc/
index.html), takes 10 minutes to learn, 5 minutes to write generator
for hungred functions.
Base& func0()
{
return C<0>();
}
Base& func1()
{
return C<1>();
}
Base& func2()
{
return C<2>();
}
....
Base& Factory::createInstance(int i) {
const Base& (*ptrs)()[]={func0,func1,func2,... /* can be filled by
Boost.Preprocessor too */};
return ptrs[i]();
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]