non-user38741
non-user38741

Reputation: 871

Is there a final, simple answer of how to detect if a function exists?

This site has 50+ post about the topic, several 'detection patterns' have had their successes through various epochs. With C++20 we should see quite some simplifications here.

So, what are the current best practices of detecting

  1. An exact signature. E.g. detect that F( int ) is defined rather than any F that takes an int via (an implicit) conversion.
  2. Callable with a given type (under the usual rules of implicit conversion)

Upvotes: 1

Views: 215

Answers (1)

Daniel
Daniel

Reputation: 31609

Basically requires expressions:

// 1
bool exists = requires(Sig &sig) { sig = thefunction; }
// 2
bool exists = requires(A a) { thefunction(a); }
// 2B
bool exists = requires(C &c, A a) { c.thefunction(a); }

Sig should be:

using Sig = RV (*) (Args); // A
using Sig = RV (Class::*) (Args); // B

Upvotes: 1

Related Questions