Skip to content

Instantly share code, notes, and snippets.

@outro56
Forked from tcbrindle/make_vector.hpp
Last active September 15, 2020 21:30
Show Gist options
  • Save outro56/5e48dfc6c61f0ffc5191c1cf6189a6c6 to your computer and use it in GitHub Desktop.
Save outro56/5e48dfc6c61f0ffc5191c1cf6189a6c6 to your computer and use it in GitHub Desktop.
#ifndef CMUOH_MAKE_VECTOR_HPP_
#define CMUOH_MAKE_VECTOR_HPP_
#include "make_vector_details.hpp"
namespace cmuoh {
template <typename T = void, typename... Args,
typename V = detail::vec_type_helper_t<T, Args...>,
typename std::enable_if<
detail::all_constructible_and_convertible<V, Args...>::value, int>::type = 0>
std::vector<V> make_vector(Args&&... args)
{
return detail::make_vector_impl<V>(std::forward<Args>(args)...);
}
} // namespace "cmuoh"
#endif //CMUOH_MAKE_VECTOR_HPP_
#ifdefine CMUOH_MAKE_VECTOR_HPP_
#include <type_traits>
#include <vector>
namespace cmuoh::detail {
template <typename T, typename...>
struct vec_type_helper {
using type = T;
};
template <typename... Args>
struct vec_type_helper<void, Args...> {
using type = typename std::common_type<Args...>::type;
};
template <typename T, typename... Args>
using vec_type_helper_t = typename vec_type_helper<T, Args...>::type;
template <typename, typename...>
struct all_constructible_and_convertible
: std::true_type {};
template <typename T, typename First, typename... Rest>
struct all_constructible_and_convertible<T, First, Rest...>
: std::conditional<
std::is_constructible<T, First>::value &&
std::is_convertible<First, T>::value,
all_constructible_and_convertible<T, Rest...>,
std::false_type>::type {};
template <typename T, typename... Args, typename std::enable_if<
!std::is_trivially_copyable<T>::value, int>::type = 0>
std::vector<T> make_vector_impl(Args&&... args)
{
std::vector<T> vec;
vec.reserve(sizeof...(Args));
using arr_t = int[];
(void) arr_t{0, (vec.emplace_back(std::forward<Args>(args)), 0)...};
return vec;
}
template <typename T, typename... Args, typename std::enable_if<
std::is_trivially_copyable<T>::value, int>::type = 0>
std::vector<T> make_vector_impl(Args&&... args)
{
return std::vector<T>{std::forward<Args>(args)...};
}
} // namespace "cmuoh::details"
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment