99
1010#include < tuple>
1111#include < iostream>
12- #include < boost/ variant.hpp >
12+ #include < variant>
1313
1414auto get_student (int id)
1515{
@@ -24,24 +24,29 @@ auto get_student(int id)
2424}
2525
2626template <size_t n, typename ... T>
27- boost::variant<T...> _tuple_index (size_t i, const std::tuple<T...>& tpl) {
28- if (i == n)
29- return std::get<n>(tpl);
30- else if (n == sizeof ...(T) - 1 )
27+ constexpr std::variant<T...> _tuple_index (const std::tuple<T...>& tpl, size_t i) {
28+ if constexpr (n >= sizeof ...(T))
3129 throw std::out_of_range (" 越界." );
32- else
33- return _tuple_index<(n < sizeof ...(T)-1 ? n+1 : 0 )>(i, tpl);
30+ if (i == n)
31+ return std::variant<T...>{ std::in_place_index<n>, std::get<n>(tpl) };
32+ return _tuple_index<(n < sizeof ...(T)-1 ? n+1 : 0 )>(tpl, i);
3433}
3534template <typename ... T>
36- boost ::variant<T...> tuple_index (size_t i, const std::tuple<T...>& tpl) {
37- return _tuple_index<0 >(i, tpl );
35+ constexpr std ::variant<T...> tuple_index (const std::tuple<T...>& tpl, size_t i ) {
36+ return _tuple_index<0 >(tpl, i );
3837}
3938
4039template <typename T>
4140auto tuple_len (T &tpl) {
4241 return std::tuple_size<T>::value;
4342}
4443
44+ template <typename T0, typename ... Ts>
45+ std::ostream & operator << (std::ostream & s, std::variant<T0, Ts...> const & v) {
46+ std::visit ([&](auto && x){ s << x;}, v);
47+ return s;
48+ }
49+
4550int main ()
4651{
4752 auto student = get_student (0 );
@@ -71,7 +76,7 @@ int main()
7176 auto new_tuple = std::tuple_cat (get_student (1 ), std::move (t));
7277
7378 // 迭代
74- for (int i = 0 ; i != tuple_len (new_tuple); ++i)
75- // 运行期索引
76- std::cout << tuple_index (i, new_tuple) << std::endl;
79+ for (int i = 0 ; i != tuple_len (new_tuple); ++i) {
80+ std::cout << tuple_index (new_tuple, i) << std::endl; // 运行期索引
81+ }
7782}
0 commit comments