The following code example tries to extract the value types of member pointer of a struct foo
previously fed into a function serialize()
.
This maybe needs further explanation: I want to eventually iterate through each member of the struct foo
and apply certain operations based on the value types of each member pointer. Have a look:
#include <cstdio>
#include <utility>
#include <tuple>
#include <typeinfo>
/* Struct with two int members */
struct foo
{
int a_;
int b_;
};
/* Saves member pointers */
template<auto Ptr>
struct proxy
{
decltype(Ptr) mem_ptr_;
};
/* Conglomerate of all member ptrs of a struct */
template <typename T>
struct type_descriptor;
template <>
struct type_descriptor<foo>
{
using type = std::tuple<proxy<&foo::a_>, proxy<&foo::b_>>;
};
/* Extract member ptr value type */
template<typename T>
struct member_pointer_value;
template<typename Class, typename Value>
struct member_pointer_value<Value Class::*>
{
using type = Value;
};
/* Iterate over each member ptr and compare */
template<typename T, std::size_t... I>
auto serialize_impl(const T& mystruct , std::index_sequence<I...> indices)
{
([](){
using value_type = member_pointer_value<decltype(std::tuple_element_t<I, typename type_descriptor<T>::type>::mem_ptr_)>::type;
printf("%s\n", typeid(value_type).name());
if constexpr (std::is_same_v<int, std::remove_cvref<value_type>>) {
printf("Is int!\n");
// ...
} else {
printf("Is not int :(\n");
// ...
}
}(), ...);
}
template <typename T, typename Indices = std::make_index_sequence<std::tuple_size_v<typename type_descriptor<T>::type>>>
auto serialize(T mystruct)
{
serialize_impl(mystruct, Indices{});
}
int main()
{
foo f0;
serialize(f0);
}
Problem:
std::is_same_v
doesn't return true in the constexpr check, so the non-int branch is taken, which is not intended. Interestingly, typeinfo (included for debug purposes only) gives me a type of "i" which I always thought of as "integer"... What is happening?
You are mixing up
std::remove_cvref
andstd::remove_cvref_t
, I believe it's a typo somehow.Demo