1

为什么编译器不能匹配FunctionF中的模板参数。invoke()有没有我不知道的非推断上下文?以及如何解决?

居住

// Invoke Function with all tuple arguments.
template<typename F, size_t... Is, typename Tuple>
auto invoke(F&& f, std::index_sequence<Is...>, Tuple&& t)
{
    return f(std::get<Is>(t)...);
}

template<typename F, typename Tuple>
auto invoke(F&& f, Tuple&& t)
{
    constexpr std::size_t uiLength = std::tuple_size_v<std::remove_reference_t<Tuple>>;
    return invoke(std::forward<F>(f),
                  std::make_index_sequence<uiLength>{},
                  std::forward<Tuple>(t));
}

template<typename T>
struct A{
   using D = int;
};
template<typename... T>
auto make(T&...){
    return std::make_tuple(A<T>{}...);
}

int main()
{
  invoke([](auto&, auto&){}, std::make_tuple(A<int>{}, A<double>{})); // works
  //auto a = invoke(make, std::make_tuple(A<int>{}, A<double>{})); // does not compile, but why??
}
4

2 回答 2

2

有没有我不知道的非推断上下文?以及如何解决?

问题是您不能将模板函数的名称作为函数的参数传递

template<typename... T>
auto make(T&...){
    return std::make_tuple(A<T>{}...);
}

// ...

auto a = invoke(make, std::make_tuple(A<int>{}, A<double>{}));

尝试重写make()为通用(和可变)lambda(这是一个对象,因此您可以将其作为参数传递给函数)

auto a = invoke([](auto & ... rData){ return std::make_tuple(A<decltype(rData)>{}...);},
                std::make_tuple(A<int>{}, A<double>{}));

题外话建议:invoke()用不同的名称重命名(myInvoke()例如)以减少与std::invoke().

于 2019-05-09T18:21:00.653 回答
0

另一种解决方案是将函数定义为静态 lambda:

static const auto makeDataHandles = [](auto&... t) {
    return std::make_tuple(A<std::remove_reference_t<decltype(t)>>{}...);
}
于 2019-05-10T06:23:28.463 回答