Last active
May 6, 2020 19:17
-
-
Save dayjaby/bbc0c275478b751b9215a1cf81024a8c to your computer and use it in GitHub Desktop.
Typelists to be used for mavlink streams in PX4
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 <iostream> | |
template<bool B, class T, class F> | |
struct conditional { typedef T type; }; | |
template<class T, class F> | |
struct conditional<false, T, F> { typedef F type; }; | |
// from https://stackoverflow.com/a/16803836 | |
template <typename... Ts> | |
struct largest_type; | |
template <typename T> | |
struct largest_type<T> | |
{ | |
using type = T; | |
}; | |
template <typename T, typename U, typename... Ts> | |
struct largest_type<T, U, Ts...> | |
{ | |
using type = typename largest_type<typename conditional< | |
(sizeof(U) <= sizeof(T)), T, U | |
>::type, Ts... | |
>::type; | |
}; | |
template<typename... Args> | |
struct pack { }; | |
// Variant 1 - use functions to do stuff with the typelists | |
// disadvantages: hard to read, have to instantiate the typelist class A to be able to call the functions | |
template<class... Args> | |
struct A | |
{ | |
using args = pack<Args...>; | |
}; | |
using x = A<int, char, double>; | |
template<typename... Args, typename A> | |
constexpr int f(pack<Args...>, A a) { return sizeof(typename largest_type<Args...>::type); } | |
template<typename A> | |
constexpr int f(A a) { return f(typename A::args(), a); } | |
// Variant 2 - using constexpr, looks more beautiful ;) | |
template<typename... Args> | |
struct MavlinkStreamTypeList { | |
using streams = pack<Args...>; | |
// could have also used an enum, but we do not live in the 2000s anymore | |
static constexpr unsigned int largest_size = sizeof(typename largest_type<Args...>::type); | |
}; | |
int main() { | |
std::cout << f<x>(x()) << std::endl; | |
std::cout << MavlinkStreamTypeList<int, char, double>::largest_size << std::endl; | |
std::cout << sizeof(largest_type<int, char, double>::type) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment