Last active
June 13, 2021 21:35
-
-
Save nabijaczleweli/37cdd8c28039ea41a999 to your computer and use it in GitHub Desktop.
Iterate over all elements of variadic template
This file contains 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 <cstddef> | |
#include <utility> | |
template<class T, class... TT> | |
struct over_all { | |
using next = over_all<TT...>; | |
static const constexpr std::size_t size = 1 + next::size; | |
template<class C> | |
inline constexpr static C for_each(C cbk, T && tval, TT &&... ttval){ | |
cbk(std::forward<T>(tval)); | |
next::for_each(cbk, std::forward<TT>(ttval)...); | |
return cbk; | |
} | |
template<class C> | |
inline constexpr C operator()(C cbk, T && tval, TT &&... ttval) const { | |
return for_each(cbk, std::forward<T>(tval), std::forward<TT>(ttval)...); | |
} | |
}; | |
template<class T> | |
struct over_all<T> { | |
static const constexpr std::size_t size = 1; | |
template<class C> | |
inline constexpr static C for_each(C cbk, T && tval) { | |
cbk(std::forward<T>(tval)); | |
return cbk; | |
} | |
template<class C> | |
inline constexpr C operator()(C cbk, T && tval) const { | |
return for_each(cbk, std::forward<T>(tval)); | |
} | |
}; |
This file contains 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 <tuple> | |
#include <vector> | |
struct yaml_reader { | |
std::vector</*Something with `clone()` function*/> handlers; // Exposition only | |
template<class... Args> | |
inline yaml_reader(Args &&... args); | |
} | |
template<class... Args> | |
inline yaml_reader::yaml_reader(Args &&... args) { | |
handlers.reserve(sizeof...(Args)); | |
over_all<Args...>::for_each([&](auto && val) { | |
handlers.emplace_back(val.clone()); | |
}, std::forward<Args>(args)...); | |
} |
Revision 4 brought a bunch of fixes & improvements!
Revision 6 made it more compile time.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Still needs polishing, but works well!