my code was
#include <iostream>
#include <list>
#include <functional>
using namespace std;
void tes(std::string s)
{
cout << "tes " << s << '\n';
}
void tes2(std::string s)
{
cout << "tes " << s << '\n';
}
void tes3(std::string s)
{
cout << "tes " << s << '\n';
}
int main()
{
using FuncType = std::function<void(std::string&)>;
std::list<std::pair<int, FuncType>> events =
{
{1, std::bind(tes, "1")},
{2, std::bind(tes2, "2")},
{3, std::bind(tes3, "3")} };
int t = 1;
auto remove_func = [&t](std::pair<int, FuncType> pair)
-> bool
{
return pair.first == t;
};
events.remove_if(remove_func);
for (auto ev : events)
{
std::cout << ev.first << ' ' ;
ev.second;
}
}
the result just display ev.first, but not the ev.second. what happened?? how to resolve this problem?? i mean display the string in FuncType function such "2" and "3". or fixed this code properly to work to display each.
CodePudding user response:
Fix the misprint:
std::cout << ev.first << ' ' << ev.second;
CodePudding user response:
There are a couple of issues in the posted code
// ...
void tes(std::string s)
{ // ^^^^^^^^^^^^^
}
// ...
using FuncType = std::function<void(std::string&)>;
// ^^^^^^^^^^^^
std::list<std::pair<int, FuncType>> events =
{
{1, std::bind(tes, "1")},
{2, std::bind(tes2, "2")},
{3, std::bind(tes3, "3")}
// ^^^^^^^^^^^^^^^^^^^^
};
The functions like tes
have one parameter of type std::string
, the alias FuncType
is a std::function
with one parameter of type std::string&
, but the pairs in events
are assigned the results of std::bind
, which have zero parameters (they are, well, binded).
Moreover, in the printing loop
for (auto ev : events)
{
std::cout << ev.first << ' ' ;
ev.second; // <- This does nothing, it should be a call.
}
The fix1 is straightforward:
using FuncType = std::function<void(void)>;
// ^^^^^^
// ...
for (auto ev : events)
{
std::cout << ev.first << ' ' ;
ev.second();
// ^^
}