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

How can I convert a reference type to a value type?

本文关键字:类型 类型转换 引用      更新时间:2023-10-16

我试图使用新的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&'编译错误。如何从指向该类型的指针中获取值类型?

您可以使用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()