我希望提取成员指针所指向的成员类型。
template<someType myClass::*member>
void demo(myClass& instance, void* ptr) {
instance.*member = *reinterpret_cast<someType*>(ptr); // can the someType in this line be deduced from member?
}
我尝试使用评论中建议的decltype
,但是我遇到了一些问题:
instance.*member= static_cast<decltype(instance.*member)>((*buffer)[offset]);
buffer
是一个 std::shared_ptr<std::vector<uint8_t>>
,
someType
是 uint32_t
我得到以下错误信息:
error: invalid static_cast from type ‘__gnu_cxx::__alloc_traits >::value_type {aka unsigned char}’ to type ‘uint32_t& {aka unsigned int&}’
据我了解,使用 member
定义为 uint32_t instance::*member
的 decltype(instance.*member)
会产生一个引用 uint32_t&
而不是 uint32_t
。我尝试通过传值的方式来传递实例,但是错误仍然存在。我知道 std::remove_reference
,但是我不明白为什么引用会首先出现。
如果我能够在没有类实例的情况下提取 someType
,那将是进一步的改进。然而,我不知道如何实现这一点,虽然通过使用 std lib,我可以获得没有指针的类:
template <T*>
struct removePointer {
typedef T type;
}
我不知道如何以一种能获取类的someType
部分的形式编写代码,而不需要事先知道这个类。我可以编写以下内容,但仍然需要显式传递类名和类型名称,是否有一种自动提取它们的方法?此外,以下代码根本无法编译(http://ideone.com/8VlKO4):
#include <iostream>
using namespace std;
template <class C,typename T, T C::*v>
struct getPointerType {
typedef T type;
};
class Test {
int value;
};
int main() {
int Test::*member=nullptr;
cout << typeid(getPointerType<Test, int, decltype(member)>::type) << std::endl;
return 0;
}
typeof
/__typeof__
。 - oakad