我正在尝试查找变量的类型。在 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'
类型不是第一类对象。您不能将类型传递给函数,而cout << decltype(x)将类型传递给函数正是如此(尽管经过运算符美化)。
要获取有关变量类型的信息,您可以
int,则不必打印它。使用此(非标准)函数模板
template <class T> void printType(const T&)
{
std::cout << __PRETTY_FUNCTION__ << "\n";
}
printType(x);
Run Code Online (Sandbox Code Playgroud)使用升压。
#include <boost/type_index.hpp>
std::cout << boost::typeindex::type_id_with_cvr<decltype(x)>().pretty_name() << "\n";
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
5055 次 |
| 最近记录: |