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

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

您可以使用std::remove_reference使其成为非引用类型:

std::numeric_limits<
    std::remove_reference<decltype(*p)>::type
>::max();

Live demo

或:

std::numeric_limits<
    std::remove_reference_t<decltype(*p)>
>::max();

稍微不那么冗长。

你想删除引用以及我猜的潜在 constness,所以你会使用

std::numeric_limits<std::decay_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