Last active
August 4, 2019 12:27
-
-
Save nbenn/fce3c4c3142459229ae5ae243a878148 to your computer and use it in GitHub Desktop.
Runtime index for choosing type
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
// compile: clang++ -Wall -std=c++14 -I /usr/local/include mp11-type-list-switch.cpp -o mp11-type-list-switch | |
#include <vector> | |
#include <iostream> | |
#include <boost/mp11/list.hpp> | |
#include <boost/mp11/algorithm.hpp> | |
namespace mp11 = boost::mp11; | |
using num_types = mp11::mp_list<int, double>; | |
template <size_t i> | |
using num_type = mp11::mp_at_c<num_types, i> | |
template<class F> | |
inline constexpr | |
decltype(std::declval<F>()(std::declval<mp11::mp_size_t<0>>())) | |
with_type(std::size_t i, F && f) { | |
return mp11::mp_with_index< mp11::mp_size<num_types> >(i, | |
std::forward<F>(f)); | |
} | |
size_t length(size_t i, size_t len) { | |
return with_type(i, [&](auto I) { | |
std::vector< num_type<I> > vec(len, 100); | |
return vec.size(); | |
}); | |
} | |
int main () { | |
std::cout << "length: " << length(0, 4) << "\n"; | |
std::cout << "length: " << length(1, 5) << "\n"; | |
std::cout << "length: " << length(2, 6) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment