update: move std::variant to container chapter

This commit is contained in:
Changkun Ou
2019-07-10 10:18:23 +02:00
parent 942dd4b528
commit fb91f1584a
3 changed files with 35 additions and 50 deletions

View File

@@ -9,7 +9,7 @@
#include <tuple>
#include <iostream>
#include <boost/variant.hpp>
#include <variant>
auto get_student(int id)
{
@@ -24,17 +24,16 @@ auto get_student(int id)
}
template <size_t n, typename... T>
boost::variant<T...> _tuple_index(size_t i, const std::tuple<T...>& tpl) {
if (i == n)
return std::get<n>(tpl);
else if (n == sizeof...(T) - 1)
constexpr std::variant<T...> _tuple_index(const std::tuple<T...>& tpl, size_t i) {
if constexpr (n >= sizeof...(T))
throw std::out_of_range("越界.");
else
return _tuple_index<(n < sizeof...(T)-1 ? n+1 : 0)>(i, tpl);
if (i == n)
return std::variant<T...>{ std::in_place_index<n>, std::get<n>(tpl) };
return _tuple_index<(n < sizeof...(T)-1 ? n+1 : 0)>(tpl, i);
}
template <typename... T>
boost::variant<T...> tuple_index(size_t i, const std::tuple<T...>& tpl) {
return _tuple_index<0>(i, tpl);
constexpr std::variant<T...> tuple_index(const std::tuple<T...>& tpl, size_t i) {
return _tuple_index<0>(tpl, i);
}
template <typename T>
@@ -42,6 +41,12 @@ auto tuple_len(T &tpl) {
return std::tuple_size<T>::value;
}
template <typename T0, typename ... Ts>
std::ostream & operator<< (std::ostream & s, std::variant<T0, Ts...> const & v) {
std::visit([&](auto && x){ s << x;}, v);
return s;
}
int main()
{
auto student = get_student(0);
@@ -71,7 +76,7 @@ int main()
auto new_tuple = std::tuple_cat(get_student(1), std::move(t));
// 迭代
for(int i = 0; i != tuple_len(new_tuple); ++i)
// 运行期索引
std::cout << tuple_index(i, new_tuple) << std::endl;
for(int i = 0; i != tuple_len(new_tuple); ++i) {
std::cout << tuple_index(new_tuple, i) << std::endl; // 运行期索引
}
}