错误:预期在“decltype”之前出现主表达式

Sam*_*mer 8 c++ windows mingw

我正在尝试查找变量的类型。在 stackoverflow 中提到了decltype()用于此目的。但是当我尝试使用它时,它会抛出我在标题中提到的错误。

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int x = 4;
    cout << decltype(x);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我预料到了int,但它显示为错误。error: expected primary-expression before 'decltype'

lub*_*bgr 6

类型不是第一类对象。您不能将类型传递给函数,而cout << decltype(x)将类型传递给函数正是如此(尽管经过运算符美化)。

要获取有关变量类型的信息,您可以

  1. 阅读代码。如果对象的类型是int,则不必打印它。
  2. 使用调试器单步调试您的程序。它显示了变量的类型。
  3. 使用此(非标准)函数模板

    template <class T> void printType(const T&)
    {
        std::cout << __PRETTY_FUNCTION__ << "\n";
    }
    
    printType(x);
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使用升压。

    #include <boost/type_index.hpp>
    
    std::cout << boost::typeindex::type_id_with_cvr<decltype(x)>().pretty_name() << "\n";
    
    Run Code Online (Sandbox Code Playgroud)