【发布时间】:2018-07-08 16:43:50
【问题描述】:
我正在编写类似下面的代码
#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);
}
很遗憾,由于以下错误,它拒绝在(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)'
是否有可能以某种方式强制它正确推断出Type?
【问题讨论】:
-
你有使用
std::function作为论据吗?如果您仅查看带有可调用参数的所有标准库函数(就像许多algorithm functions一样),它们对可调用类型使用单个模板参数,在您的情况下可能类似于@ 987654326@ -
之后,我将这些操作存储在列表中,以便稍后调用每个类型。
-
@majkrzak 您可以强制构造
std::function对象。foo(std::function<void(const int&)>(&goo)); -
有什么阻止您将模板参数添加到调用中吗?它为我编译,然后:
foo<int>([](const int&){}); -
@Someprogrammerdude 最常见的问题可能是“如何以通用方式存储 Callable”。
标签: c++ templates c++17 std-function template-argument-deduction