-1

I have a member function defined in a macro, that member only takes arguments of the same type as the current class. How can I get the current type in the macro?

I'm thinking something along the lines of

#define EQUAL() bool operator==(const decltype(*this)& b)const {return a==b.a;}

struct A{
    int a;
    EQUAL()
};

however this isn't allowed to be used in a top level context like that.

Are there any other methods for deducing the current type?

The only other idea I have is to make it a template with a static assert that it is the same but that feels hacky.

#include <type_traits>

#define EQUAL() \
template<typename T>\
bool operator==(const T& b) const { \
    static_assert(std::is_same_v<T,std::decay_t<decltype(*this)>>);\
    return a==b.a;\
}

struct A{
    int a;
    EQUAL()
};
Bomaz
  • 1,871
  • 1
  • 17
  • 22
  • 1
    I guess you have to either pass the class name or typedef it. E.g. `using self = A;`. – JulianW Aug 21 '19 at 22:10
  • See also https://stackoverflow.com/questions/21143835/can-i-implement-an-autonomous-self-member-type-in-c – Artyer Aug 21 '19 at 22:10
  • 1
    I don't see how this makes sense? Your member variable is already int, why would you want a generic compare when its going to fail unless it can implicitly convert to int? Would it not be better just to make the whole struct templated or is there some use case that I didn't consider? – Tagger5926 Aug 21 '19 at 22:21
  • Per Artyer: possible duplicate of [Can I implement an autonomous \`self\` member type in C++?](https://stackoverflow.com/questions/21143835/can-i-implement-an-autonomous-self-member-type-in-c) – Davis Herring Aug 22 '19 at 03:00

1 Answers1

1

You can modify your template solution so that it uses SFINAE instead of a static assert:

#define EQUAL \
template<typename T> \
auto operator==(const T& b) const -> std::enable_if_t< \
        std::is_same_v<T, std::decay_t<decltype(*this)>>, bool \
> { \
    return a == b.a; \
}

(You need the trailing return type otherwise this is not in scope)

This way there is a chance for other overloads to be chosen.

Artyer
  • 31,034
  • 3
  • 47
  • 75