Created
September 14, 2019 00:24
-
-
Save tristan0x/1fbbc37b48a88bd362e0b20475f11f5b to your computer and use it in GitHub Desktop.
C++11 version of https://gist.github.com/tristan0x/5bd947e8d89a187a6cbf8747b05c3ea3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <initializer_list> | |
template <int... Values> | |
struct integer_sequence {}; | |
template <std::size_t Size, int...Accu> | |
struct ones_traits { | |
using type = typename ones_traits<Size - 1, 1, Accu...>::type; | |
}; | |
template <int... Accu> | |
struct ones_traits<0, Accu...> { | |
using type = integer_sequence<Accu...>; | |
}; | |
template <typename T, int... Ones> | |
std::initializer_list<T> il_impl(T value, const integer_sequence<Ones...>&) { | |
static const auto array = { (Ones, value)... }; | |
return array; | |
} | |
template <std::size_t Size, typename T> | |
std::initializer_list<T> il(T value) { | |
return il_impl<T>(value, typename ones_traits<Size>::type()); | |
} | |
// -------------- | |
#include <iostream> | |
#include <iterator> | |
#include <vector> | |
template <typename T> | |
void print(const std::vector<T>& v) { | |
std::copy(v.begin(), v.end(), | |
std::ostream_iterator<T>(std::clog, ", ")); | |
std::clog << '\n'; | |
} | |
template <typename T> | |
void test(const std::initializer_list<T>& il) { | |
std::vector<T> v(il); | |
print(v); | |
} | |
int main() { | |
test(il<3>(3)); | |
test(il<3>(3.14957)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment