Consider the following code
#include <type_traits>
template<bool Test, class T, T val1, T val2>
constexpr T if_v = std::conditional_t<Test,
std::integral_constant<T, val1>,
std::integral_constant<T, val2>>::value;
int main()
{
constexpr size_t value1 = 123;
constexpr size_t value2 = 456;
constexpr bool test = (3 > 2);
constexpr size_t r0 = if_v<test, size_t, value1, value2>; // = 123
return 0;
}
Since we know at compile time what the types of value1
and value2
are, we should not have to specify it. So we could write
template<bool Test, auto val1, auto val2>
constexpr decltype(val1) if_v = std::conditional_t<Test,
std::integral_constant<decltype(val1), val1>,
std::integral_constant<decltype(val2), val2>>::value;
so that we can write a simplified if statement if_v<test, value1, value2>
(without the type). Ideally I'd also like to ensure that both input values are of the same type. But I am not sure how to achieve this while using auto
.
Basically, are there better ways to define if_v
such that we can write if_v<test, value1, value2>
without having to specify the type, while also somehow static_assert
ing type equality?
What about using SFINAE ?
I mean
or, maybe, simply