hi,
I have a template function <typename cT, typename tT, int n>
{
....
double array[n];
if (n==2)
binomial code
else if (n==3)
trinomial code (array[0] array[1] array[2])
else
....
compiler tries to compile the "trinomial code" code even when the template
is instantiated with n=2,
and that gives warnings because of array[2]
Well, you do know that the thing the compiler is warning you about
isn't going to cause any problems; you could consider turning the
warning off, or leaving a comment that says "the warning on this line
means nothing". Many compilers have a way to turn off specific
warnings for small portions of code, usually in the form of a #pragma
directive.
Is there a way to make the compiler ignore the non-binomial code ?
Assuming that explicit specialization of your entire function is not
acceptable (because you have a lot of other common code between the
two cases), your only other option AFAIK is to separate that part of
the code into a different function. You can use explicit
specialization of the other function, something like:
===== BEGIN CODE =====
#include <iostream>
using namespace std;
template <int n> void FillArray (double *);
template<> void FillArray<2> (double *array) {
array[0] = 1.0;
array[1] = 2.0;
}
template<> void FillArray<3> (double *array) {
array[0] = 4.0;
array[1] = 5.0;
array[2] = 6.0;
}
template <typename cT, typename tT, int n>
void FillAndPrintArray () {
double array[n];
// do things specific to array size
FillArray<n>(array);
// common code
cout << n << ": " << endl;
for (int i = 0; i < n; ++ i)
cout << array
<< endl;
}
int main (int, char **) {
FillAndPrintArray<int,int,2>();
FillAndPrintArray<int,int,3>();
return 0;
}
===== END CODE =====
There, FillArray has explicit specialization for the case of n = 2 and
n = 3. The correct one is called from FillAndPrintArray.
Note that without a default implementation of FillArray (as in the
above example), if you try calling FillAndPrintArray<...,...,4>() you
will get a linker error.
Jason