【发布时间】:2020-05-06 03:25:38
【问题描述】:
我正试图围绕 C++ lambda 表达式和模板的交互来思考。
此代码按我的预期工作:
#include <iostream>
int bar (int x, int (* f) (int))
{
return f (x);
}
double bar (double x, double (* f) (double))
{
return f (x);
}
int main ()
{
std::cout << bar (16, [] (int x) -> int { return x * x; }) << std::endl;
std::cout << bar (1.2, [] (double x) -> double { return x * x; }) << std::endl;
return 0;
}
也是这样:
#include <iostream>
#include <functional>
int bar (int x, std::function<int (int)> f)
{
return f (x);
}
double bar (double x, std::function<double (double)> f)
{
return f (x);
}
int main ()
{
std::cout << bar (16, [] (int x) -> int { return x * x; }) << std::endl;
std::cout << bar (1.2, [] (double x) -> double { return x * x; }) << std::endl;
return 0;
}
到目前为止,一切都很好。但以下示例均无法编译:
#include <iostream>
template <typename T>
T bar (T x, T (* f) (T))
{
return f (x);
}
int main ()
{
std::cout << bar (16, [] (int x) -> int { return x * x; }) << std::endl;
std::cout << bar (1.2, [] (double x) -> double { return x * x; }) << std::endl;
return 0;
}
和
#include <iostream>
#include <functional>
template <typename T>
T bar (T x, std::function <T (T)> f)
{
return f (x);
}
int main ()
{
std::cout << bar (16, [] (int x) -> int { return x * x; }) << std::endl;
std::cout << bar (1.2, [] (double x) -> double { return x * x; }) << std::endl;
return 0;
}
GCC 版本 8.3.0(带有 -std=c++17)给出错误消息:
no matching function for call to 'bar(int, main()::<lambda(int)>' (and
another for the "double" version) and "template argument
deduction/substitution failed: main()::<lambda(int)> is not derived
from std::function<T(T)>" (for the second failing example).
但是,这个任务有效:
std::function<int (int)> f = [] (int x) -> int { return x * x; };
谁能帮我解释一下? (显然,这不是实用代码。这只是一个学习尝试。)
【问题讨论】:
标签: c++ templates lambda c++17