I have a variadic template function which calls itself to determine the largest number in a list (constituted by the templatized arguments). I am trying to make a specializa
I see two mistakes using clang.
Put the overload taking a single int first.
Make things unambiguous for lists of length 1. Recall that variadic lists can have zero size and when they do, it seems to me you have an ambiguity.
This compiles and runs correctly for me:
#include <iostream>
using namespace std;
template <int N>
int tmax() {
return N;
}
template <int N, int N1, int... N2>
int tmax() {
return N > tmax<N1, N2...>() ? N : tmax<N1, N2...>();
}
int main() {
cout << tmax<32, 43, 54, 12, 23, 34>();
}
54
Since you can't partially specialize functions, you need to wrap your functionality:
template<int Head, int... Tail>
struct Tmax{
static int do(){
return Head > Tmax<Tail...>::do() ? Head : Tmax<Tail...>::do();
}
};
template<int N>
struct Tmax<N>{
static int do(){
return N;
}
};
template<int... Numbers>
int tmax(){
return Tmax<Numbers...>::do();
}
Personally, I'd prefer using static class members over functions for this sort of thing:
template <int... N> struct max;
template <int N, int... M> struct max<N, M...> {
static const int value = max<N, max<M...>::value>::value;
};
template <int N, int M> struct max<N, M> {
static const int value = N > M ? N : M;
};
int main()
{
return max<1,2,3>::value;
}
Update: Using ildjarn's suggestion, here's the less verbose version:
#include <type_traits>
template <int... N> struct max;
template <int N, int... M> struct max<N, M...>
: std::integral_constant<int, max<N, max<M...>::value>::value> { };
template <int N, int M> struct max<N, M>
: std::integral_constant<int, (N > M ? N : M)> { };