Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why this template function does not recognize the lamda's returned type?

This template function does not recognize the lamda’s returned type, even specifing it decommenting ‘->void’.

Why does it happen?

What could I do to circumvent this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include<iostream>
#include<array>
template<typename T, typename S, size_t SIZE>
void for_each(std::array<T,SIZE>& arr, S(*func)(int&))
{
    for (auto i{0}; i != arr.size(); ++i)
        func(arr[i]);
}
int main()
{
    std::array<int, 5> five_elems{10, 20, 30, 40, 50};
    for_each(five_elems, [](int& ref)/*->void*/{ref *= 2; std::cout << ref << ' '; });
    //for (auto i : five_elems)
    //    i*=2;
    for (const auto i : five_elems)
        std::cout << i << ' ';
}

>Solution :

Your for_each expects a function pointer, but the implicit conversion (from lambda to function pointer) won’t be considered in template argument deduction, which causes the calling failing.

You can perform the conversion explicitly:

for_each(five_elems, static_cast<void(*)(int&)>([](int& ref)/*->void*/{ref *= 2; std::cout << ref << ' '; }));

Or

for_each(five_elems, +[](int& ref)/*->void*/{ref *= 2; std::cout << ref << ' '; });

Or just stop using the function pointer parameter. You can add a new type template parameter and then the lambda directly.

template<typename T, size_t SIZE, typename F>
void for_each(std::array<T,SIZE>& arr, F func)
{
    for (auto i{0}; i != arr.size(); ++i)
        func(arr[i]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading