[英]How can I convert a reference type to a value type?
我正在尝试使用新的decltype
关键字将一些代码移动到模板,但是当与解除引用的指针一起使用时,它会生成引用类型。 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';
}
第一个numeric_limits
工作,但第二个抛出value-initialization of reference type 'int&'
编译错误的value-initialization of reference type 'int&'
。 如何从指向该类型的指针获取值类型?
您可以使用std::remove_reference
使其成为非引用类型:
std::numeric_limits<
std::remove_reference<decltype(*p)>::type
>::max();
要么:
std::numeric_limits<
std::remove_reference_t<decltype(*p)>
>::max();
对于稍微不那么冗长的东西。
如果你从一个指向指向类型的指针,为什么还要解除引用呢? 只是,好吧,删除指针:
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.