【发布时间】:2017-06-14 17:22:27
【问题描述】:
为什么以下代码无法编译(在 C++11 模式下)?
#include <vector>
template<typename From, typename To>
void qux(const std::vector<From>&, To (&)(const From&)) { }
struct T { };
void foo(const std::vector<T>& ts) {
qux(ts, [](const T&) { return 42; });
}
错误信息是:
prog.cc:9:5: error: no matching function for call to 'qux'
qux(ts, [](const T&) { return 42; });
^~~
prog.cc:4:6: note: candidate template ignored: could not match 'To (const From &)' against '(lambda at prog.cc:9:13)'
void qux(const std::vector<From>&, To (&)(const From&)) { }
^
但它并没有解释为什么它不能匹配参数。
如果我将qux 设为非模板函数,将From 替换为T 并将To 替换为int,它将编译。
【问题讨论】:
-
首先
qux没有返回任何东西,所以这不应该编译auto bar = qux... -
@nbro 这与手头的问题无关。
-
如果你知道这么多,你就不会问问题了。无论如何,赞成,因为我也不知道为什么。
-
非捕获 lambda 可以转换为函数指针,而不是函数引用。
-
@n.m.不幸的是,将参数更改为指针会产生相同的错误。
标签: c++ c++11 templates lambda