Hello
Can I use template to create several instantiations of some function, different only in some constant parameter? The number of alternatives for this parameter is fixed. E.g.
I want not to rewrite (where upper is in 1..32 in powers of two)
funct(param, int upper)
{
some_loops(..)
some_heavy_code_fast_for_const_and_slow_for_variable(upper)
}
into a set of
funct_with_upper_is_1(param) // upper =1
{ manually_copied_code...heavy(1) }
funct_with_upper_is_2(param) // upper =2
{ manually_copied_code...heavy(2) }
funct_with_upper_is_4(param) // upper =4
{ manually_copied_code...heavy(4) }
funct_with_upper_is_8(param) // upper =8
{ manually_copied_code...heavy(8) }
but into templated
template<int upper>
funct_with_fixed_upper(param)
{ the_original_code....heavy(upper) }
and then
template<upper=1> funct_with_fixed_upper(param);
template<upper=2> funct_with_fixed_upper(param);
template<upper=4> funct_with_fixed_upper(param);
template<upper=8> funct_with_fixed_upper(param);
Is this possible with C++ tempaltes?
== Verbose mode on ==
I have a lot C++ files with code like that
function_typical(long long double ***A, long long double ***B, int const_1, int const_2)
// the type "long long double" here is very correct, this is extension of compiler
{
for(int i=1;i<100000-1;i++)
for(int j=1;j<100000-1;j++)
for(int k=0;k<const_1;k++)
for(int l=k;l<const_2;l++) {
// some cray work with array like
A[i][j][l-k]+=(B[i][j][l-k]+A[i+1][j][l-k]+A[i][j+1][l-k]-A[i-1][j][k]-A[i][j-1][l-k]/2.2)/88.3;
if(A[i][j][l-k]>sin_lld(A[i][j-1][l-k])){B[i][j][l-k]=A[i][j][k]*4;}
}
}
This is just an example, but:
- I can't interchange the loops;
- the 2 outer loops, i & j have a lot of iterations
- the 2 inner (nested), k& l have a bit of iterations, number of which is passed into the
function_typical
and the set of them are fixed, e.g. const_1 and const_2 is one of pairs: (2,3), (4,5), (3,5). Total number of allowed pairs is smaller then 10.
The problem with this code is its speed is very low. If I will fix const_1 and const_2 in this code to numberic constants, compiler will do a great job in optimizing (e.g unrolling all k and all l iterations, doing a some smart job).
But I physically can't change every typical-like function of every set of (const_1 and const_2) pair. Also, constant propagator of compiler can't propagate constants of the set info the function (this is a networking server and the client does a selection of some const_1 and const_2 pair form fixed set).
So I know in compile-time all the alternatives of pairs. But I have no chance of rewrite every function by hand.
== verbose mode off ==
Thanks in advance