Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if member is declared in class

Is it possible to check if a member variable, a member function, or a type definition is declared in a given class?

Various questions on StackOverflow talk about checking if a given class merely contains a member, essentially using std::is_detected. But all these solutions detect the member also in derived classes, which may not declare the member themselves.

For example, the following doesn't compile.

#include <experimental/type_traits>

struct base
{
  using type = std::true_type;
};

struct derived : public base { };

template<typename T>
using has_type_t = typename T::type;

template<typename T>
constexpr inline bool has_type_v =         
std::experimental::is_detected<has_type_t, T>::value;

int main ()
{
  static_assert (has_type_v<base>);
  static_assert (!has_type_v<derived>);
}

Can any changes be made so that the two assertions hold? Or is reflection needed for that?

like image 375
Toby Brull Avatar asked Jan 25 '18 10:01

Toby Brull


Video Answer


1 Answers

I don't see a way for type or static member, but for regular member, you can have distinguish base::m from derived::m:

template<typename T>
using has_m_t = decltype(&T::m);

template<typename T>
constexpr inline bool has_m_v =
    std::experimental::is_detected_exact<int (T::*), has_m_t, T>::value;

And the test:

struct base { int m; };
struct derived : public base {};
struct without {};

static_assert( has_m_v<base>);
static_assert(!has_m_v<derived>);
static_assert(!has_m_v<without>);

Demo

like image 51
Jarod42 Avatar answered Oct 19 '22 15:10

Jarod42