Loading...
Searching...
No Matches
tryInvoke.h File Reference
+ Include dependency graph for tryInvoke.h:
+ This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

template<class Ret >
constexpr auto TfNotInvoked ()
 Return the result type of TfTryInvoke<Ret> in the case where the function was not invoked – false if Ret is void, otherwise an empty std::optional<Ret>.
 
template<class Ret , class Fn , class... Args>
auto TfTryInvoke (Fn &&fn, Args &&...args)
 Invoke fn with args if fn is invocable with those arguments and return a result that indicates both whether the call was made and, if so, what it returned.
 

Function Documentation

◆ TfNotInvoked()

constexpr auto TfNotInvoked ( )
constexpr

Return the result type of TfTryInvoke<Ret> in the case where the function was not invoked – false if Ret is void, otherwise an empty std::optional<Ret>.

Call this when you need to produce the same result type as TfTryInvoke in a context where the function was not called.

See also
TfTryInvoke

Definition at line 26 of file tryInvoke.h.

◆ TfTryInvoke()

auto TfTryInvoke ( Fn &&  fn,
Args &&...  args 
)

Invoke fn with args if fn is invocable with those arguments and return a result that indicates both whether the call was made and, if so, what it returned.

The template parameter Ret specifies the expected return type of fn:

  • If fn is invocable and Ret is non-void, invoke fn and return std::optional<Ret> containing the result.
  • If fn is invocable and Ret is void, invoke fn and return true.
  • If fn is not invocable with args, return TfNotInvoked<Ret>() – an empty std::optional<Ret> or false.

The return value is always truthy if fn was invoked and falsy if it was not, regardless of whether Ret is void.

Use this to build operations over heterogeneous collections where a callable may only handle a subset of element types:

auto process = [](std::string const &s) { return s.size(); };
// Invocable -- returns optional<size_t> containing the result.
auto r1 = TfTryInvoke<size_t>(process, std::string("hello"));
TF_AXIOM(r1 && *r1 == 5);
// Not invocable -- returns empty optional<size_t>.
auto r2 = TfTryInvoke<size_t>(process, 42);
TF_AXIOM(!r2);
#define TF_AXIOM(cond)
Aborts if the condition cond is not met.
Definition: diagnostic.h:193
See also
TfNotInvoked

Definition at line 68 of file tryInvoke.h.