gla*_*des 1 c++ templates typeid member-pointers template-meta-programming
下面的代码示例尝试提取foo先前输入到函数中的结构的成员指针的值类型serialize()。
这可能需要进一步解释:我想最终迭代结构体的每个成员foo,并根据每个成员指针的值类型应用某些操作。看一看:
#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);
}
Run Code Online (Sandbox Code Playgroud)
问题:
std::is_same_v在 constexpr 检查中不返回 true,因此采用非 int 分支,这不是预期的。有趣的是,typeinfo(仅用于调试目的)给了我一个“i”类型,我一直认为它是“整数”......发生了什么?
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |