I'm attempting to write a function that forces constexpr
evaluation via. a template. I wrote this, but it works only for int
(beware, will give recursion depth errors with GCC):
#include <iostream>
template<int val>
constexpr int force_constexpr() { return val; }
constexpr int triangle(int n)
{
return n ? n + triangle(n - 1) : 0;
}
int main(void)
{
std::cout << force_constexpr<triangle(0x200)>() << '\n';
}
Note that this is for demonstration purposes only; I know that the triangle number can be calculated with (n+1)*n/2
.
Then I attempted to write a generic function, however, that doesn't work as well. This is a plain error (not surprising, as it uses T
before T
is defined):
template<T val, typename T = decltype(val)>
constexpr T force_constexpr() { return val; }
as is this (which obviously won't work; it's a nested template):
template<typename T>
template<T val>
constexpr T force_constexpr() { return val; }
and this requires the type of the argument to be passed:
template<typename T, T val>
constexpr T force_constexpr() { return val; }
How can I do this without passing the type as a parameter to the template? Or, in other words, how can I deduce a template parameter type?
I'm looking for a C++11 solution but solutions for other standards are welcome.