【问题标题】:How can I convert a reference type to a value type?如何将引用类型转换为值类型?
【发布时间】:2015-02-25 13:46:14
【问题描述】:

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

【问题讨论】:

    标签: c++ c++11 reference decltype


    【解决方案1】:

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

    对于一些稍微不那么冗长的东西。

    【讨论】:

      【解决方案2】:

      如果你是从一个指针指向指向的类型,为什么还要解引用它呢?只是,好吧,删除指针:

      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
      【解决方案3】:

      你想删除引用以及可能constness 我猜,所以你会使用

      std::numeric_limits<std::decay_t<decltype(*p)>>::max()
      

      【讨论】:

      • 他为什么要完全删除constness? std::numeric_limits worksconst T 类型完美搭配。
      猜你喜欢
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多