Skip to content

has_public_data_member, has_public_member_function? #106

@baryluk

Description

@baryluk

It can be probably implemented in a library, not in the base standard, but I found no way to implement it (using get_public_member_functions), after spending 3 hours trying.

I want just:

  if constexpr (std::reflect::has_public_member_function<reflect(declype(a))>("foo")) {
     a.foo(5);
  }

or something equivalently short.

D language has this using:

  static if (__traits(hasMember, a, "foo")) {
    a.foo(x);
  }

and

  static if (__traits(compiles, a.foo(0))) {
    a.foo(x);
  }

(there is also a library helper for the first one:

  static if (std.traits.hasMember!(typeof(a), "foo")) {
    a.foo(x);
  }

)

See https://dlang.org/spec/traits.html#hasMember and https://dlang.org/phobos/std_traits.html#hasMember

This can be done in C++ with contepts, but the problem with concept is that it must be first defined out of the place it is used, making the usage harder:

template <class T>
concept HasFoo = requires (T t) { t.foo(0); };

/// some other code


  if constexpr (HasFoo<decltype(a)>) {
    a.foo(x);
  }

which is far from acceptable. This is because concepts cannot be defined locally in functions.

So I believe this deserves specialization, or at least a defined utility to extract by name from ObjectSequence (in case of overloaded functions in a aggregate type, would be fine to emit compile error).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions