I'm trying to insert std::bind as function pointer into std::map so that in later stages I can replace std::placeholders::_1 with actual parameters based on the conditions.
Below is the function pointer declaration:
typedef int (*funcptr)(std::string, int *);
And this is how I insert into the map.
const std::map<std::string, std::pair<int, funcptr >> lookup {
{ ------ >function pointer as element to the map
"aclk",
{
1, std::bind(getParam,NONE,std::placeholders::_1)
} ---------------------------------------------------> this part
}
};
Full code:
#include <random>
#include <iostream>
#include <memory>
#include <functional>
#define NONE "0"
std::pair<int, int> getParam(std::string, int *){
return std::make_pair(1,9);
}
typedef std::pair<int,int> (*funcptr)(std::string, int *);
const std::map<std::string, std::pair<int, funcptr>> lookup {
{
"aclk",
{
1, std::bind(getParam,NONE,std::placeholders::_1)
}
}
};
int main()
{
auto f = std::get<1>(lookup.second);
int a[5] = {1,2,3,4,5};
f(a);
}
MY Question:
One or other I'm getting struck with the compilation errors with the above approach.
Error I'm facing right now is:
g++ -std=c++0x bind.cpp
try.cpp:14: error: expected initializer before ‘<’ token
line 14 in the code is
try.cpp:14: const std::map<std::string, std::pair<int, funcptr>> lookup {
As was stated in comments, std::bind
returns callable object - it is unnamed class which has operator()(args)
and it cannot be casted to pointer to function. You need to use std::function
as wrapper.
Another issue, string is bound when std::bind
is called, so final functor will take only int*
, typedef for funcptr
may be:
typedef std::function< std::pair<int,int>(int*) > funcptr;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.