微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

没有匹配函数调用可变参数模板函数

如何解决没有匹配函数调用可变参数模板函数

代码如下

#include <iostream>
#include <functional>

using namespace std;
template<class F,class ...Args>
result_of_t<F> foo(F&& f,Args&&... args){
    cout<<sizeof...(args);
    f(args...);
}

int main(){
    foo([](char a){ cout<<a<<'\n'; },'a');
    return 0;
}

我在编译代码时说

template.cpp:12:38: error: no matching function for call to ‘foo(main()::<lambda(char)>,char)’

完整的编译错误如下

template.cpp: In function ‘int main()’:
template.cpp:12:38: error: no matching function for call to ‘foo(main()::<lambda(char)>,char)’
   12 |  foo([](char a){ cout<<a<<'\n'; },'a');
      |                                      ^
template.cpp:6:16: note: candidate: ‘template<class F,class ... Args> std::result_of_t<F> foo(F&&,Args&& ...)’
    6 | result_of_t<F> foo(F&& f,Args&&... args){
      |                ^~~
template.cpp:6:16: note:   template argument deduction/substitution Failed:
In file included from /usr/include/c++/10.2.0/bits/move.h:57,from /usr/include/c++/10.2.0/bits/nested_exception.h:40,from /usr/include/c++/10.2.0/exception:148,from /usr/include/c++/10.2.0/ios:39,from /usr/include/c++/10.2.0/ostream:38,from /usr/include/c++/10.2.0/iostream:39,from template.cpp:1:
/usr/include/c++/10.2.0/type_traits: In substitution of ‘template<class _Tp> using result_of_t = typename std::result_of::type [with _Tp = main()::<lambda(char)>]’:
template.cpp:6:16:   required by substitution of ‘template<class F,Args&& ...) [with F = main()::<lambda(char)>; Args = {char}]’
template.cpp:12:38:   required from here
/usr/include/c++/10.2.0/type_traits:2570:11: error: invalid use of incomplete type ‘class std::result_of<main()::<lambda(char)> >’
 2570 |     using result_of_t = typename result_of<_Tp>::type;
      |           ^~~~~~~~~~~
/usr/include/c++/10.2.0/type_traits:2344:11: note: declaration of ‘class std::result_of<main()::<lambda(char)> >’
 2344 |     class result_of;
      |           ^~~~~~~~~

为什么主函数的第一条语句与函数不匹配?

解决方法

因为无法推断出返回类型foo

result_of带有函子的完整签名,那里缺少Args ..

template<class F,class ...Args>
result_of_t< F(Args...) > foo(F&& f,Args&&... args){
    cout<<sizeof...(args);
    f(args...);
}

Demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。