[英]how to get the type of a pointer in C++11
我有以下几点:
type* ptr;
我想从ptr
type
ptr
。 我尝试使用declval
/ declval
/ decay
但无法使其正常工作(当您对自己正在做的事情不了解时会发生这种情况)。
因此,如何获取类型并创建相同类型的变量-如type some_var;
您可以使用std::remove_pointer
类型特征:
using ptr_type = int*;
using type = std::remove_pointer<ptr_type>::type;
static_assert(std::is_same<type, int>::value, "");
另外,您可以使用decltype
和std::declval
:
using ptr_type = int*;
using type = decltype(*std::declval<ptr_type>());
static_assert(std::is_same<type, int>::value, "");
如果您直接在decltype
内使用解引用表达式,则可能还需要使用std::remove_reference
:
int* ptr = nullptr;
std::remove_reference<decltype(*ptr)>::type var = 7;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.