c++ for each 遍历tuple
#include <iostream>
#include <tuple>
//c++11寫法
namespace detail
{
?? ?template<int... Is>
?? ?struct seq { };
?? ?template<int N, int... Is>
?? ?struct gen_seq : gen_seq<N - 1, N - 1, Is...> { };
?? ?template<int... Is>
?? ?struct gen_seq<0, Is...> : seq<Is...> { };
}
namespace detail
{
?? ?template<typename T, typename F, int... Is>
?? ?void for_each_c11(T&& t, F f, seq<Is...>)
?? ?{
?? ??? ?auto l = { (f(std::get<Is>(t)),0)... };
?? ?}
}
template<typename... Ts, typename F>
void for_each_in_tuple_c11(std::tuple<Ts...> const& t, F f)
{
?? ?detail::for_each_c11(t, f, detail::gen_seq<sizeof...(Ts)>());
}
//c++14
template<typename T, typename F, int... Is>
void for_each_c14(T&& t, F f,std::integer_sequence<int,Is...>)
{
?? ?auto l = { (f(std::get<Is>(t)),0)... };
}
template<typename... Ts, typename F>
void for_each_in_tuple_c14(std::tuple<Ts...> const& t, F f)
{
?? ?for_each_c14(t, f,std::make_integer_sequence<int,sizeof...(Ts)>());
}
int main()
{
?? ?auto datas = std::make_tuple<int>(1, 2, 3, 4);
?? ?std::apply([](auto&& ... args) {
?? ??? ?((std::cout << args << std::endl),...);
?? ??? ?}, datas);
?? ?std::cout << "....." << std::endl;
?? ?for_each_in_tuple_c11(datas,[](auto value) {
?? ??? ?std::cout << value << std::endl;
?? ??? ?});
?? ?std::cout << "....." << std::endl;
?? ?for_each_in_tuple_c14(datas, [](auto value) {
?? ??? ?std::cout << value << std::endl;
?? ??? ?});
}
總結
以上是生活随笔為你收集整理的c++ for each 遍历tuple的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenGL 入门第一课 视窗以及三角形
- 下一篇: iframe父页面与子页面之间的元素获取