PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

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

 November 05, 2022     c++, lambda, templates     No comments   

Issue

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?

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


Answered By - songyuanyao
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing