在宏中引用类C++

Refer to class in C++ macro

本文关键字:C++ 引用      更新时间:2023-10-16

我想写

struct Foo{
    MY_MACRO
};

并将其扩展到

struct Foo{
    void bar(Foo&){}
};

如何定义MY_MACRO?

我唯一能想到的是以下内容:

#define MY_MARCO(X) void bar(X&){}
struct Foo{
    MY_MACRO(Foo)
};

这非常接近,但并不理想,因为我不想重复类名。

不幸的是,以下内容无法编译:

struct Foo{
    void bar(decltype(*this)&){}
};

这与这个问题密切相关。答案是,您(还)不能编写使用您所在的类定义类型的东西。您必须编写一个宏,其中包含类定义的开始(即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");
    }
};