Date: Mon, 27 Oct 2025 13:03:05 +0000
On Mon, Oct 27, 2025 at 12:13 PM Jonathan Wakely wrote:
>
> This is problematic for arbitrary types, which might not be default constructible. In generic code, you don't know how to construct a value to return.
>
> But you can return std::type_identity<int>{} or std::type_identity<double>{} and then use decltype(select_type<1>())::type.
#include <type_traits>
#include <semaphore>
template<int N> consteval auto select_type_detail(void)
{
/**/ if constexpr ( 0 == N ) return (int *)nullptr;
else if constexpr ( 1 == N ) return (double *)nullptr;
else if constexpr ( 2 == N ) return (std::binary_semaphore*)nullptr;
}
template<int N>
using select_type = std::remove_pointer_t< decltype(
select_type_detail<N>() ) >;
#include <iostream>
#include <typeinfo>
int main(void)
{
select_type<2> var(0);
std::cout << typeid(var).name() << std::endl;
}
>
> This is problematic for arbitrary types, which might not be default constructible. In generic code, you don't know how to construct a value to return.
>
> But you can return std::type_identity<int>{} or std::type_identity<double>{} and then use decltype(select_type<1>())::type.
#include <type_traits>
#include <semaphore>
template<int N> consteval auto select_type_detail(void)
{
/**/ if constexpr ( 0 == N ) return (int *)nullptr;
else if constexpr ( 1 == N ) return (double *)nullptr;
else if constexpr ( 2 == N ) return (std::binary_semaphore*)nullptr;
}
template<int N>
using select_type = std::remove_pointer_t< decltype(
select_type_detail<N>() ) >;
#include <iostream>
#include <typeinfo>
int main(void)
{
select_type<2> var(0);
std::cout << typeid(var).name() << std::endl;
}
Received on 2025-10-27 13:02:41
