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

5

我正在尝试使用新的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&' 的编译错误。我该如何从指向该类型的指针获取值类型?
3个回答

13
你可以使用 std::remove_reference 来使其成为非引用类型:
std::numeric_limits<
    std::remove_reference<decltype(*p)>::type
>::max();

实时演示

或者:

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

为了让内容更加简洁,可以使用以下方式。

7

如果您要从指针转换为指向的类型,那么为什么还要解引用呢?只需直接删除指针即可:

std::cout << std::numeric_limits<std::remove_pointer_t<decltype(p)>>::max() << '\n';
// or std::remove_pointer<decltype(p)>::type pre-C++14

如果 OP 没有 C++14,请在 ::type 中返回已翻译的文本。 - vsoftco

5
您想要删除引用,还可能涉及到去除常量性。我猜您需要使用:std::remove_referencestd::remove_const
std::numeric_limits<std::decay_t<decltype(*p)>>::max()

他为什么要去掉const呢?std::numeric_limits可以很好地处理const T类型。这里演示了它的完美表现。 - Shoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接