为什么我不能将 lambda 传递给这个采用 std::函数的函数?
Why can't I pass a lambda to this function which takes a std::function?
以下程序是非法的,我想了解原因:
#include <functional>
#include <iostream>
template<typename Result, typename Arg>
void deduce(std::function<Result(Arg)> f)
{
std::cout << "Result: " << typeid(Result).name() << std::endl;
std::cout << "Arg: " << typeid(Arg).name() << std::endl;
}
int main()
{
auto f = [](int x)
{
return x + 1;
};
deduce(f);
return 0;
}
clang
的输出:
$ clang -std=c++11 test.cpp
test.cpp:48:3: error: no matching function for call to 'deduce'
deduce(f);
^~~~~~
test.cpp:26:6: note: candidate template ignored: could not match 'function<type-parameter-0-1 (type-parameter-0-0)>' against '<lambda at test.cpp:34:13>'
void deduce(std::function<T2(T1)> f)
^
1 error generated.
似乎我应该能够将我的 lambda 转换为deduce
收到的std::function
.为什么编译器在这种情况下无法应用适当的转换?
问题是,虽然接受int
并返回int
的lambda可以转换为std::function<int(int)>
,但它的类型不是std::function<int(int)>
而是我认为的任意实现定义的类型。
可以通过告诉编译器所需的类型来解决此问题。 然后转换将按预期进行。
auto f = [](int x){ return x + 1; };
deduce<int, int>(f); // now ok
或者,明确说明f
的静态类型。
std::function<int(int)> f = [](int x){ return x + 1; };
deduce(f); // now also ok
相关文章:
- 无法引用该函数" std:: variant <_Types...> operator =",因为此函数已被删除
- 错误:使用已删除的函数"std::unique_ptr<...>
- 我有模板功能.通过使用函数std::for_each,用这个容器中的最大数字替换每个正数
- 如何使用函数std::min()来计算最小值
- 删除了 g++ 在 linux 中basic_stringstream函数 std
- 如何在 c++ 中使用返回类型导出函数 std::map
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic() [_Tp = node]"
- 使用 SFINAE 检查函数 std::to_string 是否存在类型
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 为什么函数 std::basic_streambuf::setg() 需要非常量 agruments
- C++将已删除的函数 std::unique_ptr 与基类一起使用
- 奇怪的错误:当没有真正创建指针时,使用已删除的函数'std::unique_ptr<_Tp,_Dp>::unique_ptr
- 通过模板构造函数(std ::功能和迷你案例)将构造函数触发
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic()
- 错误:使用已删除的函数std::basic_ofstream(OpenCV和C++11)
- 类成员容器迭代器在成员函数std::find中不兼容,但为什么不兼容呢
- 没有构造函数 std::istream_iterator 的实例
- 错误:没有与参数列表匹配的重载函数"std::make_shared"实例
- 错误:使用已删除的函数"std::thread::thread(const std::thread&)"
- 不能在没有对象的情况下调用成员函数 std::string class::function()