请看下面的C++代码,可以很好地编译(gcc 10.1.0):-
#include <iostream>
#include <string>
#include <functional>
template <class T = std::string>
void foo(T src, std::function<void(T&& t)> completionFn)
{
completionFn(std::move(src));
}
int main(int argc, char *argv[])
{
foo<std::string>("hello", [] (auto && t) {
std::cout << t << std::endl;
});
return 0;
}
如果修改主函数以删除对“foo”的调用中的模板参数,即使我具有默认模板参数,它也不再编译,因此我无法弄清原因。int main(int argc, char *argv[])
{
foo<>("hello", [] (auto && t) {
std::cout << t << std::endl;
});
return 0;
}
我可能缺少明显的东西。这是编译器的输出:-
src/scanner_test.cpp: In function ‘int main(int, char**)’:
src/scanner_test.cpp:19:6: error: no matching function for call to ‘foo(const char [6], main(int, char**)::<lambda(auto:11&&)>)’
19 | });
| ^
src/scanner_test.cpp:10:6: note: candidate: ‘template<class T> void foo(T, std::function<void(T&&)>)’
10 | void foo(T src, std::function<void(T&& t)> completionFn)
| ^~~
src/scanner_test.cpp:10:6: note: template argument deduction/substitution failed:
src/scanner_test.cpp:19:6: note: ‘main(int, char**)::<lambda(auto:11&&)>’ is not derived from ‘std::function<void(T&&)>’
19 | });
我想念什么?谢谢!抱歉,这是一个愚蠢的问题。
最佳答案
仅当无法根据上下文确定模板时,才使用默认模板参数。在给定foo<>("hello", ...)
的上下文中,将模板T确定为const char [6]
(如错误消息中所给)。对于函数,与函数中实际参数相关的模板参数将始终如此。
您可能正在寻找的解决方案是:
#include <iostream>
#include <string>
#include <functional>
template <class T>
void foo(T src, std::function<void(std::string&& t)> completionFn)
{
//NOTE cast here to std::string, ensures we always have an std::string
completionFn(std::move((std::string&)src));
}
int main(int argc, char *argv[])
{
foo("hello", [] (std::string&& t) {
std::cout << t << std::endl;
});
return 0;
}
关于c++ - 为什么对同时在lambda参数中使用的函数使用默认模板参数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62894315/