参考C++宏中的class
Refer to class in C++ macro
我要写
struct Foo{
MY_MACRO
};
并将其扩展为
struct Foo{
void bar(Foo&){}
};
如何定义 MY_MACRO?
我唯一能想到的是:
#define MY_MARCO(X) void bar(X&){}
struct Foo{
MY_MACRO(Foo)
};
这非常接近,但不太理想,因为我不想重复 class 名称。
很遗憾,以下内容无法编译:
struct Foo{
void bar(decltype(*this)&){}
};
这与this question密切相关。答案是你不能(还)写一些东西来使用你所在的 class 定义的类型。你将不得不写一个包含 class 定义开头的宏(即struct Foo)
和一些促进 typedef 的机制。
但您可以在 static_assert 中使用 decltype(*this)
。即:
#include <type_traits>
struct Foo {
template <typename T>
void bar(T& t) {
static_assert(std::is_same<T&, decltype(*this)>::value,
"bar() only accepts objects of same type");
}
};
我要写
struct Foo{
MY_MACRO
};
并将其扩展为
struct Foo{
void bar(Foo&){}
};
如何定义 MY_MACRO?
我唯一能想到的是:
#define MY_MARCO(X) void bar(X&){}
struct Foo{
MY_MACRO(Foo)
};
这非常接近,但不太理想,因为我不想重复 class 名称。
很遗憾,以下内容无法编译:
struct Foo{
void bar(decltype(*this)&){}
};
这与this question密切相关。答案是你不能(还)写一些东西来使用你所在的 class 定义的类型。你将不得不写一个包含 class 定义开头的宏(即struct Foo)
和一些促进 typedef 的机制。
但您可以在 static_assert 中使用 decltype(*this)
。即:
#include <type_traits>
struct Foo {
template <typename T>
void bar(T& t) {
static_assert(std::is_same<T&, decltype(*this)>::value,
"bar() only accepts objects of same type");
}
};