[英]Using decltype like typedef
Experimenting with decltype
to be used in place of a typedef
or auto
keywords whenever deemed necessary. 在必要时尝试使用
decltype
代替typedef
或auto
关键字。 Some of them ( stl and user function ) works however it doesn't work directly with a user defined object. 其中一些(stl和user function)有效,但是不能直接与用户定义的对象一起使用。 Please I need an explanation here.
请在这里我需要一个解释。
#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";
}
EDITED EDITED
vector<foo> foos;
decltype(foos) b; //works :tested with vc++ compiler
decltype(vector<foo>) b; //fails
decltype
is equivalent to the declaration type of its object operand(or a dummy object). decltype
等效于其对象操作数(或虚拟对象)的声明类型。 So you feed it with an object and get the class at compile time. 因此,您为它提供了一个对象,并在编译时获取了该类。 Since the result is a type, you can use it wherever a
typename
is expected. 由于结果是一个类型,你可以用它无论一个
typename
的预期。 You can't feed it with a type. 您不能使用类型来输入。 https://en.cppreference.com/w/cpp/language/decltype
https://en.cppreference.com/w/cpp/language/decltype
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.