Is is possible to get a value in a constexpr environment for any type in a generic way, even if the type is not default constructible? If not, why?
As an example, i want to get the index of a type in a std::variant
in a constexpr function.
Forgive my misuse of std::is_default_constructible
(i used it as a generic, default constructible typeholder), but the name somehow still fits :D
#include <utility>
#include <type_traits>
#include <variant>
//how i made it work without default constructible types..
template <typename T, typename Variant>
constexpr auto index_ugly() {
return [&]<size_t... I>(std::index_sequence<I...>) {
return std::variant<std::is_default_constructible<
std::variant_alternative_t<I, Variant>>...>{
std::is_default_constructible<T>{}}
.index();
}(std::make_index_sequence<std::variant_size_v<Variant>>{});
}
//how it could look like if i could generate a value
//for the type T regardless of its default constructibility
template<typename T, typename Variant>
constexpr auto index() {
return Variant{T{}}.index();
}
struct X {
X (int) {}
};
constexpr int a = index<X, std::variant<int, double, X>>();