Last active
November 25, 2024 17:15
-
-
Save IvanaGyro/7804ef097275b4510249156d55980dfd to your computer and use it in GitHub Desktop.
Dynamically get type traits of the data type.
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 <tuple> | |
#include <array> | |
#include <complex> | |
using TypeList = std::tuple<void, double, std::complex<float>, int, bool>; | |
template <typename T> | |
struct SizeOf{ | |
static constexpr size_t value = sizeof(T); | |
}; | |
// specialization for suppressing warning | |
template <> | |
struct SizeOf<void>{ | |
static constexpr size_t value = 0; | |
}; | |
template <template<typename > typename IsType, typename Tuple> | |
struct TypeTraitsHelper; | |
template <template<typename > typename IsType, typename... Ts> | |
struct TypeTraitsHelper<IsType, std::tuple<Ts...>> { | |
static constexpr std::array<decltype(IsType<void>::value), sizeof...(Ts)> value{IsType<Ts>::value...}; | |
}; | |
template <template<typename > typename IsType> | |
auto constexpr TypeTraits = TypeTraitsHelper<IsType, TypeList>::value; | |
bool constexpr is_float(int dtype) { | |
if (dtype >= std::tuple_size_v<TypeList>) { | |
return false; | |
} | |
return TypeTraits<std::is_floating_point>[dtype]; | |
} | |
size_t constexpr typeSize(int dtype) { | |
if (dtype >= std::tuple_size_v<TypeList>) { | |
return 0; | |
} | |
return TypeTraits<SizeOf>[dtype]; | |
} | |
template <typename Tuple, template <typename> typename Component> | |
struct transform_tuple; | |
template <typename... Ts, template <typename> typename Component> | |
struct transform_tuple<std::tuple<Ts...>, Component> { | |
using type = std::tuple<Component<Ts>...>; | |
}; | |
int main() { | |
std::cout << is_float(0) << "\n"; // std::is_floating_point_v<void> = false | |
std::cout << is_float(1) << "\n"; // std::is_floating_point_v<double> = true | |
std::cout << typeSize(0) << "\n"; // sizeof(void) = 0 | |
std::cout << typeSize(1) << "\n"; // sizeof(double) = 8 | |
std::cout << typeSize(2) << "\n"; // sizeof(std::complex<float>) = 8 | |
std::cout << typeSize(3) << "\n"; // sizeof(int) = 4 | |
std::cout << typeSize(4) << "\n"; // sizeof(bool) = 1 | |
std::cout << typeSize(100) << "\n"; // 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment