4

I want to enable/disable branches at compile time depending of whether a function can be called with certain arguments. What has to go in the if constexpr condition? I can get the result type via std::result_of(decltype(add)(A, B)), but how can I check, whether the result type is valid? (i.e. how to I convert this information to a bool?)

const auto add = [](const auto a, const auto b) { return a + b; };

const auto subtract = [](const auto a, const auto b) { return a - b; };

template <typename A, typename B>
void foo(A a, B b) {

  if constexpr ( /* can add(a, b) be called? */ ) {
    std::cout << "result of add: " << add(a, b) << std::endl;
  }

  if constexpr ( /* can subtract(a, b) be called? */ ) {
    std::cout << "result of subtract: " << subtract(a, b) << std::endl;
  }
}
jfrohnhofen
  • 167
  • 9
  • How would you check whether `add` or `subtract` can be called without the `constexpr` restriction? – UnholySheep Feb 27 '18 at 18:15
  • It does not have to be a `constexpr`, but the check should be compile time. `decltype(add(a, b))` gives a substitution error for invalid combinations of types. I want to use that error as the condition – jfrohnhofen Feb 27 '18 at 18:23

2 Answers2

4

First you need to make your lambdas SFINAE-friendly.

#define RETURNS(...)\
  noexcept(noexcept(__VA_ARGS__))\
  ->decltype(__VA_ARGS__)\
  { return __VA_ARGS__; }

const auto add = [](const auto a, const auto b) RETURNS( a + b );

const auto subtract = [](const auto a, const auto b) RETURNS( a - b );

Now add and subract can be tested in a SFINAE context.

namespace details {
  template<class, class, class...>
  struct can_invoke:std::false_type {};
  template<class F, class...Args>
  struct can_invoke<F, std::void_t< std::result_of_t< F&&(Args&&...) > >, Args... >:
    std::true_type
  {};
}
template<class F, class...Args>
using can_invoke_t = details::can_invoke<F, Args...>;

template<class F, class...Args>
constexpr can_invoke_t< F, Args... >
can_invoke( F&&, Args&&... ){ return {}; }

and we are ready:

template <typename A, typename B>
void foo(A a, B b) {

  if constexpr ( can_invoke( add, a, b ) ) {
    std::cout << "result of add: " << add(a, b) << std::endl;
  }

  if constexpr ( can_invoke( subtract, a, b ) {
    std::cout << "result of subtract: " << subtract(a, b) << std::endl;
  }
}

this is ; in it is more awkward, in more elegant as they already have a can invoke type trait (which handles a few more corner cases; however, it also expects you to call add with std::invoke).


In I sort of like this trick:

template<class F>
constexpr auto invoke_test( F&& ) {
  return [](auto&&...args) ->
  can_invoke_t<F, decltype(args)...>
  { return {}; };
}

template <typename A, typename B>
void foo(A a, B b) {

  if constexpr ( invoke_test( add )( a, b ) ) {
    std::cout << "result of add: " << add(a, b) << std::endl;
  }

  if constexpr ( invoke_test( subtract )( a, b ) {
    std::cout << "result of subtract: " << subtract(a, b) << std::endl;
  }
}

where invoke_test takes a callable, and returns a callable whose only job is to answer "the original callable be invoked with the args you passed me".

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • As an aside, `invoke_test` can be extended to a compile-time optional `Maybe`, but I'm uncertain how well `if constexpr` supports side-effects-only-if-true. Probably not well. ;) – Yakk - Adam Nevraumont Feb 27 '18 at 20:04
  • Where you say is C++14, well, it can`t be, because you use if constexpr and that is C++17. – LeDYoM Oct 23 '19 at 06:48
3

You can put SFINAE to the return type and let function overloading tell whether a call can be made. A helper function can_be_called can be implemented as following:

#include <type_traits>

template<class Func, class... Args>
constexpr auto
can_be_called(Func&& func, Args&&... args)
    -> decltype(
            (std::forward<Func>(func)(std::forward<Args>(args)...)
            , bool{}))
{ return true; }

struct Dummy {
    template<class T> constexpr Dummy(T&&) {}
};

template<class... Args>
constexpr bool 
can_be_called(Dummy, Args&&...) { return false; }

// test
#include <iostream>
void foo(int, int) {}

struct A{};

int main() {
    if constexpr( can_be_called(foo, 1, 2) ) {
        std::cout << "OK\n";
    }

    if constexpr ( !can_be_called(foo, A{}, 2) ) {
        std::cout << "NO\n";
    }
}
llllllllll
  • 16,169
  • 4
  • 31
  • 54