Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
¿Por qué esta función de plantilla no reconoce el tipo devuelto por lamda?

Esta función de plantilla no reconoce el tipo devuelto por la lamda, incluso especificándolo descomentando '->void'.

¿Por que sucede?

¿Qué podría hacer para sortear este problema?

 #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 << ' '; }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Su for_each espera un puntero de función, pero la conversión implícita (de lambda a puntero de función) no se considerará en la deducción del argumento de la plantilla , lo que hace que la llamada falle.

Puede realizar la conversión explícitamente:

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

O

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

O simplemente deje de usar el parámetro de puntero de función. Puede agregar un nuevo parámetro de plantilla de tipo y luego la lambda directamente.

 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]); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!