Auto return functions and template creation

When writing the template code, I ran into errors <unresolved overloaded function type>that can be summarized as follows.

template <int N>
auto bar()
{
    return N;
}

int main(int, char* [])
{
    auto foo = [] (auto func) {
            return func();
        };

    foo(bar<3>);
}

With mistakes:

unresolved_overload.cpp: In function 'int main(int, char**)':
unresolved_overload.cpp:26:28: error: no match for call to '(main(int, char**)::<lambda(auto:1)>) (<unresolved overloaded function type>)'
     std::cout << foo(bar<3>) << std::endl;
                            ^
unresolved_overload.cpp:21:29: note: candidate: template<class auto:1> constexpr main(int, char**)::<lambda(auto:1)>::operator decltype (((const main(int, char**)::<lambda(auto:1)>*)((const main(int, char**)::<lambda(auto:1)>* const)0))->operator()(static_cast<auto:1&&>(<anonymous>))) (*)(auto:1)() const
     auto foo = [] (auto func) {
                             ^
unresolved_overload.cpp:21:29: note:   template argument deduction/substitution failed:
unresolved_overload.cpp:26:28: note:   couldn't deduce template parameter 'auto:1'
     std::cout << foo(bar<3>) << std::endl;
                            ^
unresolved_overload.cpp:21:29: note: candidate: template<class auto:1> main(int, char**)::<lambda(auto:1)>
     auto foo = [] (auto func) {
                             ^
unresolved_overload.cpp:21:29: note:   template argument deduction/substitution failed:
unresolved_overload.cpp:26:28: note:   couldn't deduce template parameter 'auto:1'
     std::cout << foo(bar<3>) << std::endl;

If we replace auto-return with an explicit return type,, intthis example will be compiled.

Why does autostart start in these problems? I looked at the output and replacement of the template argument, but the search was mostly fruitless. I thought this might have something to do with the order in which the / etc template was instantiated, but I couldn't understand it too much ...

+4
source share
2 answers

AndyG GCC. 64194. 2014 . , , GCC , , .

- (, , using).

+2

:

template <typename func>
auto bar(func&& f)->decltype(f())
{   
    return f();
}


int main()
{
    int i = 100;
    auto f = [=]()
    {
      return i;
    };

    bar(f);

    return 0;
 } 
0

Source: https://habr.com/ru/post/1693499/


All Articles