简体   繁体   English

如何将引用类型转换为值类型?

[英]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();

Live demo 现场演示

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.

相关问题 如何将 LPARAM 值转换为我传递的类型 - how to convert LPARAM value to the type I passed 如何使用类型特征将函数的通用引用参数限制为r值引用? - How can I use type traits to limit the universal reference parameters of a function to r-value references? 为什么我不能使用引用类型作为容器类型的值类型? - Why can't I use reference types as the value type of a container type? 如何找到字符串类型vector中存在的值的类型? - How can I find the type of the value present in vector of type string? 如何创建 value_type 类型特征? - How can I create a value_type type trait? 如何使用decltype获取引用的类型? - How can I use decltype to get the type of a reference? 如何在不取消引用的情况下将指向不完整类型的指针转​​换为对不完整类型的引用 - How to convert a pointer to an incomplete type to a reference to an incomplete type with no dereferencing 我可以确定右值引用的类型吗? - Can I determine the type of an rvalue reference? 我可以返回引用返回类型的指针吗? - Can I return a pointer in a reference return type? 使用auto和decltype使函数返回其类的类型。 如何使其返回值而不是引用? - Using auto and decltype for making a function return the type of its class. How can I make it return a value, instead of a reference?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM