C++ Lambdas 和 Variadic 模板包装器
C++ Lambdas and Variadic Templated Wrappers
我正在尝试用 C++ 执行以下代码。该程序将没有捕获的 lambda 转换为函数指针。
#include <utility>
template <typename R, typename... Args>
R run(R (*func)(Args...), Args&&... args) {
func(std::forward<Args>(args)...);
}
int main() {
run([] (int x, int y) {
return x + y;
}, 100, 200);
return 0;
}
但是,当我编译它时,出现以下错误-
test.cc: In function ‘int main()’:
test.cc:11:20: error: no matching function for call to ‘run(main()::<lambda(int, int)>, int, int)’
}, 100, 200);
^
test.cc:11:20: note: candidate is:
test.cc:4:3: note: template<class R, class ... Args> R run(R (*)(Args ...), Args&& ...)
R run(R (*func)(Args...), Args&&... args) {
^
test.cc:4:3: note: template argument deduction/substitution failed:
test.cc:11:20: note: mismatched types ‘R (*)(Args ...)’ and ‘main()::<lambda(int, int)>’
}, 100, 200);
^
据我所知,这很好。我还尝试在 run
的调用中明确给出模板参数。那也不行。
有什么想法吗?
lambda 是不是函数指针。它不能被推导为函数指针。这是一个闭包。但是,如果(且仅当)它没有捕获,它可以通过 some sorcery:
显式转换为函数指针
run(+[] (int x, int y) {
// ^^^
return x + y;
}, 100, 200);
就是说,最好让 run
接受一个任意的可调用函数:
template <typename F, typename... Args>
auto run(F func, Args&&... args)
-> decltype(func(std::forward<Args>(args)...)) // only for C++11
{
return func(std::forward<Args>(args)...);
}
我正在尝试用 C++ 执行以下代码。该程序将没有捕获的 lambda 转换为函数指针。
#include <utility>
template <typename R, typename... Args>
R run(R (*func)(Args...), Args&&... args) {
func(std::forward<Args>(args)...);
}
int main() {
run([] (int x, int y) {
return x + y;
}, 100, 200);
return 0;
}
但是,当我编译它时,出现以下错误-
test.cc: In function ‘int main()’:
test.cc:11:20: error: no matching function for call to ‘run(main()::<lambda(int, int)>, int, int)’
}, 100, 200);
^
test.cc:11:20: note: candidate is:
test.cc:4:3: note: template<class R, class ... Args> R run(R (*)(Args ...), Args&& ...)
R run(R (*func)(Args...), Args&&... args) {
^
test.cc:4:3: note: template argument deduction/substitution failed:
test.cc:11:20: note: mismatched types ‘R (*)(Args ...)’ and ‘main()::<lambda(int, int)>’
}, 100, 200);
^
据我所知,这很好。我还尝试在 run
的调用中明确给出模板参数。那也不行。
有什么想法吗?
lambda 是不是函数指针。它不能被推导为函数指针。这是一个闭包。但是,如果(且仅当)它没有捕获,它可以通过 some sorcery:
显式转换为函数指针 run(+[] (int x, int y) {
// ^^^
return x + y;
}, 100, 200);
就是说,最好让 run
接受一个任意的可调用函数:
template <typename F, typename... Args>
auto run(F func, Args&&... args)
-> decltype(func(std::forward<Args>(args)...)) // only for C++11
{
return func(std::forward<Args>(args)...);
}