no matching function call for variadic template function

Viewed 84

the code is as follows

#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;
}

while I compile the code, it says

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

the full compilation error is as follows

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, class ... Args> std::result_of_t<F> foo(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;
      |           ^~~~~~~~~

why the first statement of main function cannot match the function?

1 Answers

Because return type of foo cannot be deduced.

result_of takes full signature of functor, Args.. is missing there.

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

Demo

Related