passing an array as a nontype template parameter

Hi,

I want to know if there is way to pass a compile time constant array as a template parameter.
The purpose for that is to take benefits of optimisation which could be done by the compiler itself (arithmetic optimisations for example) with generic code.

Example: (sorry for the syntax, as it is only a fictional code)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <int SIZE, int ARRAY[SIZE]>
int compute(int* array)
{  int result = 0;
   for (int i = 0; i < SIZE; i++)
   {
       result += ARRAY[i] * array[i];
   }
   return result;
}


int main()
{
   int array[] = { 6, 8, 9, 23 };
   int result1 = compute<4,{1,2,0,3}>(&array[0]);
   int result2 = compute<4,{4,3,1,2}>(&array[0]);
}

When ARRAY[i]=0, then the computation is skipped, =1: no multiplication, =2: shift instead of multiplication, and so on....
Last edited on
No.

1
2
3
4
5
template< typename T, size_t N >
T compute( T (&a1)[ N ], T (&a2)[ N ] )
{
  // Your code here
}


It is very likely that with compiler optimizations turned on, your for() loop
will get optimized away completely (end check included) if N == 0.

Last edited on
Thanks, that is the point where I am currently.
It gives a good optimisation with few efforts when I use a good compiler.
But I use a lot of fixed array as first parameter and these arrays have a lot of "0" in some time consuming calculations.

I am asking if variadic templates or constexpr could help or any new other features which will arrive...
You might want to look at the boost::mpl library (www.boost.org). It has the ability to build compile-time arrays/sets/lists, etc, which might help you accomplish what you want. Otherwise I am not aware of any
current or upcoming C++ feature that would help you.
Topic archived. No new replies allowed.