[英]How can I convert a reference type to a value type?
I'm trying to move some code to templates using the new decltype
keyword, but when used with dereferenced pointers, it produces reference type. 我正在尝试使用新的
decltype
关键字将一些代码移动到模板,但是当与解除引用的指针一起使用时,它会生成引用类型。 SSCCE: SSCCE:
#include <iostream>
int main() {
int a = 42;
int *p = &a;
std::cout << std::numeric_limits<decltype(a)>::max() << '\n';
std::cout << std::numeric_limits<decltype(*p)>::max() << '\n';
}
The first numeric_limits
works, but the second throws a value-initialization of reference type 'int&'
compile error. 第一个
numeric_limits
工作,但第二个抛出value-initialization of reference type 'int&'
编译错误的value-initialization of reference type 'int&'
。 How do I get a value type from a pointer to that type? 如何从指向该类型的指针获取值类型?
You can use std::remove_reference
to make it a non-reference type: 您可以使用
std::remove_reference
使其成为非引用类型:
std::numeric_limits<
std::remove_reference<decltype(*p)>::type
>::max();
or: 要么:
std::numeric_limits<
std::remove_reference_t<decltype(*p)>
>::max();
for something slightly less verbose. 对于稍微不那么冗长的东西。
If you are going from a pointer to the pointed-to type, why bother dereferencing it at all? 如果你从一个指向指向类型的指针,为什么还要解除引用呢? Just, well, remove the pointer:
只是,好吧,删除指针:
std::cout << std::numeric_limits<std::remove_pointer_t<decltype(p)>>::max() << '\n';
// or std::remove_pointer<decltype(p)>::type pre-C++14
你想删除引用以及我猜的潜在的const
,所以你要使用
std::numeric_limits<std::decay_t<decltype(*p)>>::max()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.