“#define TYPE(x) typename decltype(x)”是个坏主意吗?
Is "#define TYPE(x) typename decltype(x)" a bad idea?
定义
是个坏主意吗
#define TYPE(x) typename decltype(x)
作为在 C++11 中获取变量 class 成员类型的快速方法?
理由:
考虑以下(过度简化的)示例:
#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;
}
也就是说,我有一个 class 和一些成员类型 "mtype" 和一个函数 returns 我是这个 class 的一个实例。多亏了 auto,我不必担心 class 的名称,只要我知道我的函数可以完成它的工作。但是,有时我必须定义一个特定类型的变量,为了方便起见,在我的 class.
中有一个 "mtype" 的类型定义
如果我只有变量名"a"但我知道这个变量有这个class,我可以做
typename decltype(a)::mtype b;
定义一个类型为A::mtype的变量b。
现在将此 "typename decltype" 放入宏中是个坏主意吗?是否有明显的、常见的情况会崩溃?有没有更好的方法可以快速掌握这种类型?
奖励:"a::mtype" 最好 - 是否有理由将其定义为标准中的 "decltype(a)::mtype"?
是的,这很糟糕。使用 template-using 代替:
template<class T>
using mtype_t = typename T::mtype;
用法:
auto a = make();
mtype_t<decltype(a)> b = 3;
定义
是个坏主意吗#define TYPE(x) typename decltype(x)
作为在 C++11 中获取变量 class 成员类型的快速方法?
理由:
考虑以下(过度简化的)示例:
#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;
}
也就是说,我有一个 class 和一些成员类型 "mtype" 和一个函数 returns 我是这个 class 的一个实例。多亏了 auto,我不必担心 class 的名称,只要我知道我的函数可以完成它的工作。但是,有时我必须定义一个特定类型的变量,为了方便起见,在我的 class.
中有一个 "mtype" 的类型定义如果我只有变量名"a"但我知道这个变量有这个class,我可以做
typename decltype(a)::mtype b;
定义一个类型为A::mtype的变量b。
现在将此 "typename decltype" 放入宏中是个坏主意吗?是否有明显的、常见的情况会崩溃?有没有更好的方法可以快速掌握这种类型?
奖励:"a::mtype" 最好 - 是否有理由将其定义为标准中的 "decltype(a)::mtype"?
是的,这很糟糕。使用 template-using 代替:
template<class T>
using mtype_t = typename T::mtype;
用法:
auto a = make();
mtype_t<decltype(a)> b = 3;