Alex Rivera | Logout

Non-type variadic function templates in C++11

Asked 2011-10-24T14:36:55.823
33

I saw a blog post which used non-type variadic templates (currently not supported by gcc, only by clang).

template <class T, size_t... Dimensions>
struct MultiDimArray { /* ... */ };

The example in the post compiles fine but I failed to get it to work with function templates.

Can anyone help figuring out the correct syntax (if such exists)?

int max(int n) { return n; } // end condition

template <int... N> // replacing int... with typename... works
int max(int n, N... rest) // !! error: unknown type name 'N'
{
    int tmp = max(rest...);
    return n < tmp? tmp : n;
}

#include <iostream>
int main() 
{
   std::cout << max(3, 1, 4, 2, 5, 0) << std::endl;   
}
Edit
Report

1 Answer

18

This will print out all elements, get max could be implemented similarly

template <int N>
void foo(){
  cout << N << endl;
}

template <int N, int M, int ... Rest>
void foo(){
  cout << N << endl;
  foo<M, Rest...>();
}


int main(){
  foo<1, 5, 7>();

  return 0;
}
answered 2012-12-15T07:14:00.377

Your Answer