Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

has_public_data_member, has_public_member_function? #106

Open
baryluk opened this issue Mar 18, 2022 · 1 comment
Open

has_public_data_member, has_public_member_function? #106

baryluk opened this issue Mar 18, 2022 · 1 comment

Comments

@baryluk
Copy link

baryluk commented Mar 18, 2022

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).

@baryluk
Copy link
Author

baryluk commented Mar 18, 2022

Actually maybe this could work:

  if constexpr (requires(T& t) {t.foo(0);}) {
    a.foo(x);
  }

or even

  if constexpr (requires{a.foo(0);}) {
    a.foo(x);
  }

or inline using requires requires

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant