使用具有尾随 return 类型的 lambda 尝试 SFINAE 时出现硬错误

Hard error when attempting SFINAE with lambda that has trailing return type

我在 SO 上看到了解释为什么 SFINAE 不适用于 lambda return 类型的答案。我稍微改变了我的设计,但现在收到一个更奇怪的错误。我不知道我错过了什么。代码将使用 C++11、14 和 17 进行编译。我有一些与 C++17 兼容的 apply

#include <algorithm>
#include <vector>
#include <functional>
#include <tuple>
#include <utility>

template <typename ...T>
struct S {
  std::vector<std::tuple<T...>> things;
  template <typename F>
  typename std::enable_if<std::is_same<
    typename std::invoke_result<
      std::apply<F, T...>, F, T...>::type, bool>::value,
      bool>::type
  find_if(const F &f) {
      return std::any_of(things.begin(), things.end(),
      [&](const std::tuple<T...> &t) {
          return std::apply(f, t);
      });
  }
  template <typename F>
  auto find_if(const F &f) -> decltype(std::declval<F>()(things.front())) {
      return std::any_of(things.begin(), things.end(),
      [&](const std::tuple<T...> &t) { return f(t); });
  }
};

void f() {
    S<int, float> s;
    auto l = [](const std::tuple<int, float> &) -> bool { return false; };
    s.find_if(l);
}

我的目的是调用正确的谓词。如果predicate只有一个std::tuple<Ts...>类型的参数,那么直接调用它。如果谓词参数列表与解压缩的模板参数包匹配,则调用那个。

GCC 和 Clang 都抱怨第一种方法,其中 apply 不是类型。

<source>:13:26: error: type/value mismatch at argument 1 in template parameter list for 'template<class _Functor, class ... _ArgTypes> struct std::invoke_result'
   13 |       std::apply, F, T...>::type, bool>::value,
      |                          ^
<source>:13:26: note:   expected a type, got 'std::apply'

元函数 std::invoke_result 期望作为第一个参数的是可调用对象的类型,以及参数的类型。

不幸的是,std::apply 不是类型,而是函数。另外,std::apply 是为了使用类型推导,所以它对 sfinae 不友好。

解决方案是使用可调用对象的类型而不是应用调用。

template <typename ...T>
struct S {
    std::vector<std::tuple<T...>> things;

    template <typename F, typename std::enable_if_t<
        std::is_same_v<std::invoke_result_t<F, T...>, bool>, int> = 0>
    auto find_if(const F &f) -> bool {
        return std::any_of(things.begin(), things.end(),
        [&](const std::tuple<T...> &t) {
            return std::apply(f, t);
        });
    }
};

此外,您的 lambda 应该如下所示:

[](int, float) -> bool { return false; };

这是因为 apply 正在分解元组。