Created
December 15, 2016 17:04
-
-
Save neomantra/1fb590f3c1975ed9c8318f109f7e4170 to your computer and use it in GitHub Desktop.
experiment with tuple iteration, boost::fusion versus manual template recursion.
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 <iostream> | |
#include <boost/fusion/adapted/std_tuple.hpp> | |
#include <boost/fusion/algorithm/iteration/for_each.hpp> | |
struct One { | |
int value() const { return 1+rand(); } | |
}; | |
struct Two { | |
int value() const { return 2+rand(); } | |
}; | |
struct Three { | |
int value() const { return 3+rand(); } | |
}; | |
struct OneTwoThree { | |
template <size_t T> | |
using IC = std::integral_constant<size_t, T>; | |
typedef std::tuple<One, Two, Three> Tuple; | |
OneTwoThree() | |
: m_tuple(One(), Two(), Three()) | |
{} | |
int sumFusion() const { | |
int sum = 0; | |
boost::fusion::for_each(m_tuple, [&sum](auto& number) { | |
sum += number.value(); | |
}); | |
return sum; | |
} | |
int sumRecursion(IC<std::tuple_size<Tuple>::value>) { | |
return 0; | |
} | |
template <size_t I = 0> | |
int sumRecursion(IC<I> = IC<0>()) { | |
return std::get<I>(m_tuple).value() + sumRecursion(IC<I + 1>()); | |
} | |
Tuple m_tuple; | |
}; | |
int main(int argc, const char* argv[]) { | |
auto ott = OneTwoThree(); | |
std::cout << ott.sumFusion() << " " << ott.sumRecursion() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment