无法推导出std :: function模板参数

4 c++ templates std-function template-argument-deduction c++17

我正在研究类似下面的代码

#include <functional>

template <typename Type>
void foo(const std::function<void(const Type&)> & handler) {}

void goo (const int&){}

int main() {
    foo([](const int&){});
    foo(goo);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,由于跟随错误,它拒绝编译(clang 6.0.0和gcc 8.1.1)

candidate template ignored: could not match 'function<void (const type-parameter-0-0 &)>' against '(lambda at test3.cpp:13:9)'
candidate template ignored: could not match 'function<void (const type-parameter-0-0 &)>' against '(lambda at test3.cpp:13:9)'
Run Code Online (Sandbox Code Playgroud)

有可能以某种方式迫使它Type正确演绎吗?

max*_*x66 5

你标记了C++ 17,所以你可以使用演绎指南std::function.

您可以尝试以下方法

template <typename F,
          typename Type = typename decltype(std::function{std::declval<F>()})::argument_type>
void foo (F f)
 {
 }
Run Code Online (Sandbox Code Playgroud)

我知道argument_type在C++ 17中已弃用,但您可以用简单的自定义模板替换它.

以身作则

template <typename>
struct firstArg;

template <typename R, typename A0, typename ... As>
struct firstArg<std::function<R(A0, As...)>>
 { using type = A0; };
Run Code Online (Sandbox Code Playgroud)

并且foo()可以写成

template <typename F,
          typename FUNC = decltype(std::function{std::declval<F>()}),
          typename Type = typename firstArg<FUNC>::type>
void foo (F f)
 {
 }
Run Code Online (Sandbox Code Playgroud)

这样,callable f不是一个std::function但它是原始类型(根据你的确切要求,这可能更好或更差); 如果你需要它std::function,你可以foo()使用再次扣除指南或FUNC类型在函数内获得它

template <typename F,
          typename FUNC = decltype(std::function{std::declval<F>()}),
          typename Type = typename firstArg<FUNC>::type>
void foo (F f)
 {
   FUNC fnc{f};
 }
Run Code Online (Sandbox Code Playgroud)