【问题标题】:What the type is auto & x = const int *?auto & x = const int * 是什么类型?
【发布时间】:2017-10-19 00:21:54
【问题描述】:

main函数中,我创建了一个const int指针的变量,将它赋值给auto&声明的变量。然后使用decltype(x) 检查类型。我预计类型是const int*。但是is_same 返回false

int main()
{
    int a = 10;
    const int * cp_val= &a;
    auto& x = cp_val;
    bool is_const_int_ptr = std::is_same<decltype(x), const int *>::value; // returns 0

    // *x = 100; // error: assignment of read-only location '* x'
}

但是如果我添加以下辅助函数:

#include <boost/type_index.hpp>

template<typename T> 
void print_type(T)
{cout << "type T is: "<< boost::typeindex::type_id_with_cvr<T>().pretty_name()<< '\n';}

主要是调用函数

print_type(x); // It returns int const*

我在std::is_same 中遗漏了什么吗?

【问题讨论】:

    标签: c++ c++11 auto type-deduction


    【解决方案1】:

    请注意,对于auto&amp; x,您将x 明确声明为引用;那么它的类型应该是const int *&amp;,即指向const int的指针的引用。

    这是一个更好的主意(来自 Effective Modern C++ (Scott Meyers)),可以在编译时从编译错误消息中获取准确的类型。

    template <typename>
    struct TD;
    

    然后将其用作

    TD<decltype(x)> td;
    

    你会收到类似的错误信息

    source_file.cpp:15:21: error: implicit instantiation of undefined template 'TD<const int *&>'
        TD<decltype(x)> td;
                        ^
    

    LIVE

    您的辅助函数按值获取参数;参数的引用性将在类型推导中被忽略,这就是你得到const int*的原因。

    【讨论】:

      【解决方案2】:

      模板参数推导和auto 密切相关:声明auto x = e; 赋予xf(e) 相同的类型将赋予T 在发明的函数template &lt;typename T&gt; f(T); 中,同样对于auto&amp;f(T&amp;)const auto*f(const T*)

      因此,要从 Boost 中得到正确答案,需要声明:

      template <typename T> void print_type(T&);
      //                                   ^^^^
      

      x 的类型当然是const int*&amp;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-06
        • 2020-07-03
        • 1970-01-01
        • 2010-11-30
        • 1970-01-01
        • 2011-04-28
        • 2010-11-11
        相关资源
        最近更新 更多