I want to select one of the standard containers with one template parameter at compile time. Something like
template<typename T>
void foo()
{
using Container = std::conditional_t< std::is_same_v<T, int>,
std::vector, // T is int
std::set>; // any other T
Container<T> bar;
}
How to do this properly?
The simplest way seems to be
using Container = std::conditional_t< std::is_same_v<T, int>,
std::vector<T>, // T is int
std::set<T>>;
Container bar;
std::conditional_t
allows you to select a type. There is no standard conditional template that would allow to select a template. You can write one if you want but this won't be convenient to use.
template <bool t, template <typename...> typename X, template <typename...> typename Y>
struct conditional_template;
template <template <typename...> typename X, template <typename...> typename Y>
struct conditional_template<true, X, Y>
{
template <typename... ts> using type = X<ts...>;
};
template <template <typename...> typename X, template <typename...> typename Y>
struct conditional_template<false, X, Y>
{
template <typename... ts> using type = Y<ts...>;
};
template <typename... ts>
using Container = conditional_template<true, std::list, std::vector>::type<ts...>;
Container<int> x;
It doesn't seem possible to define an analogue of std::conditional_t
convenience alias.