Overloads the function by delegating
template <int X>
class Int
{
};
template <int X>
int funcSwitch(int y, Int<X>)
{
return X + funcSwitch(y, Int<X-1>());
}
int funcSwitch(int y, Int<0>)
{
return y;
}
template<int X>
int func(int y)
{
return funcSwitch(y, Int<X>());
}
int main()
{
std::cout << func<1>(2);
return 0;
}
You need to be careful not to define Int
in another namespace than funcSwitch
, because then the call in the first funcSwitch
would not find the second funcSwitch
case when it is instantiated (this is because of a rule called ADL). To not think about this, you can also write a class template to delegate to
template<int X>
struct FuncImpl {
int operator()(int y) const {
return X + FuncImpl<X-1>()(y);
}
};
template<>
struct FuncImpl<0> {
int operator()(int y) const {
return y;
}
};
template<int X>
int func(int y)
{
return FuncImpl<X>()(y);
}
int main()
{
std::cout << func<1>(2);
return 0;
}
In general I prefer the technique without a class, because it allows for member functions to still access *this
and its private members if func
were a member function.
To be complete, there is also "explicit specialization" for functions, but because of its limits and pitfalls, I would not recommend it. In this case it would work and would be
template<int X>
int func(int y)
{
return X + func<X-1>(y);
}
template <>
int func<0>(int y)
{
return y;
}
int main()
{
std::cout << func<1>(2);
return 0;
}