使用像typedef这样的decltype

Using decltype like typedef

本文关键字:decltype typedef      更新时间:2023-10-16

尝试在必要时使用decltype代替typedefauto关键字。其中一些(stl和用户函数(工作,但它不能直接与用户定义的对象一起工作。请我在这里需要解释。

#include <iostream>
#include <vector>
using namespace std;
struct foo {
void operator=(const int a ) { val_ =a;}
int get() const { return val_;}
private:
int val_;
}; 
ostream& operator << (ostream& os, foo f )
{
os << f.get();
return os;
}
foo func()
{
foo a;
return a;
}
int main()
{
vector<foo> foos;
decltype(foos) b; //works
decltype(foo);//  don't work  - says - error C3553: decltype expects an expression not a type
decltype(func()) a; //works
a = 100;
std::cout << a << " n";
}

编辑

vector<foo> foos;
decltype(foos) b; //works :tested with vc++ compiler

decltype(vector<foo>) b; //fails

>decltype等效于其对象操作数(或虚拟对象(的声明类型。因此,您向它提供一个对象并在编译时获取该类。由于结果是一个类型,因此可以在任何需要typename的地方使用它。你不能用类型来喂它。 https://en.cppreference.com/w/cpp/language/decltype