auto&x = const int *的类型是什么?

What the type is auto & x = const int *?

本文关键字:类型 是什么 int const auto      更新时间:2023-10-16

在一个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中遗漏了什么吗?

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

这是一个更好的主意(来自有效的现代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;
                    ^

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

模板参数推导和auto密切相关:auto x = e;给出x的声明与f(e)在发明的函数template <typename T> f(T);中给T的类型相同,对于auto&f(T&)const auto*f(const T*)等也是如此。

因此,要从 Boost 获得正确答案,您需要声明:

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

x的类型当然是const int*&.