考虑以下代码
#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;
}
由于我们在编译时知道 value1
和 value2
的类型是什么,因此我们不必指定它。所以我们可以写
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;
这样我们就可以编写一个简化的if语句if_v<test, value1, value2>
(不带类型)。理想情况下,我还想确保两个输入值的类型相同。但我不确定如何在使用 auto
时实现这一目标。
基本上,是否有更好的方法来定义 if_v
,以便我们可以编写 if_v<test, value1, value2>
而无需指定类型,同时还能以某种方式实现 static_assert
类型相等?
最佳答案
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.
使用 SFINAE 怎么样?
我是说
template <bool Test, auto v1, auto v2,
std::enable_if_t<std::is_same_v<decltype(v1), decltype(v2)>, int> = 0>
constexpr auto if_v = std::conditional_t<Test,
std::integral_constant<decltype(v1), v1>,
std::integral_constant<decltype(v2), v2>>::value;
或者,也许,只是
template <bool Test, auto v1, auto v2,
std::enable_if_t<std::is_same_v<decltype(v1), decltype(v2)>, int> = 0>
constexpr auto if_v = Test ? v1 : v2;
关于C++ Type Traits if_v(自动类型推导+确保类型相同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64954991/