Cla*_*ius 2 c++ decltype typename c-preprocessor c++11
定义是一个坏主意
#define TYPE(x) typename decltype(x)
Run Code Online (Sandbox Code Playgroud)
作为在C++ 11中获取变量类的成员类型的快速方法?
理由:
请考虑以下(过度简化)示例:
#include <iostream>
#define TYPE(x) typename decltype(x)
class A {
public:
typedef int mtype;
void set(mtype const& x) { foo = x; }
mtype get() { return foo; }
private:
mtype foo;
};
A make() { return A(); }
int main() {
auto a = make();
TYPE(a)::mtype b = 3;
a.set(b);
std::cout << a.get() << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
也就是说,我有一个类成员类型为"mtype"的类,以及一个返回此类实例的函数.感谢auto,只要我知道我的函数完成它的工作,我就不必担心类的名称.但是,在某一点上,我必须定义一个特定类型的变量,为方便起见,我的类中有一个typedef为"mtype".
如果我只有变量名"a",但我知道这个变量有这个类,我可以做
typename decltype(a)::mtype b;
Run Code Online (Sandbox Code Playgroud)
定义类型为A :: mtype的变量b.
现在把这个"typename decltype"放到一个宏中是个坏主意吗?是否存在明显的常见情况?有没有更好的方法来快速达到这种类型?
额外奖励:"a :: mtype"最好 - 有没有理由在标准中没有定义为"decltype(a):: mtype"?
orl*_*rlp 12
是的,这很糟糕.使用模板代替:
template<class T>
using mtype_t = typename T::mtype;
Run Code Online (Sandbox Code Playgroud)
用法:
auto a = make();
mtype_t<decltype(a)> b = 3;
Run Code Online (Sandbox Code Playgroud)