I have a class with a list of function pointers. These function pointers point to a member function of a sub-class, which was bound like this:
functionList.push_back(std::bind(&SubClass::function, this, std::placeholders::_1, std::placeholders::_2));
Now, when copying the class with functionList, the function pointers still point to the old class. How can I rebind the function pointer to the new class?
Here an example code:
#include <vector>
#include <functional>
class SomeClass
{
};
class testClass
{
public:
typedef std::function<void(const SomeClass& var1, const SomeClass& var2)> transitionFunction;
testClass(){}
testClass(const testClass&s)
{
for(transitionFunction func : s.functionList)
{
// how to rebind the function pointer to the new this?
functionList.push_back("???");
}
}
std::vector<transitionFunction> functionList;
};
class SubClass : public testClass
{
SubClass()
{
functionList.push_back(std::bind(&SubClass::function, this, std::placeholders::_1, std::placeholders::_2));
}
void function(const SomeClass& var1, const SomeClass& var2)
{
}
};
Thanks!
You have to copy your subclass. Actually - you just need default initialization in your copy constructor:
class SubClass : public testClass
{
...
SubClass(const SubClass&) : SubClass()
{}
...
};
In case, your example is very simplified example, then you need to have own function
class with rebind
function.
[UPDATE]
Remember that rebinding is duty of your subclass - so, I'd do something like this:
Your base class should just have default copy (you might not specify this - default is default):
class testClass
{
public:
...
testClass(const testClass&s) = default;
...
};
Next step is to implement rebinding in your subclass:
class SubClass : public testClass
{
public:
using transitionFunctionRebindable =
std::function<void(SubClass*, const SomeClass&, const SomeClass&)>;
struct FunctionWrapper
{
void operator()(const SomeClass& var1, const SomeClass& var2)
{
function(thisObject, var1, var2);
}
SubClass* thisObject;
transitionFunctionRebindable function;
};
transitionFunction rebind(transitionFunction& function)
{
FunctionWrapper* fr = function.target<FunctionWrapper>();
if (fr)
{
return FunctionWrapper{this, fr->function};
}
else
{
// in case your base class added something out of your control
return function;
}
}
Construction change a little:
SubClass()
{
functionList.push_back(FunctionWrapper{this, std::bind(&SubClass::function, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)});
}
Then, copy in your subClass:
SubClass(const SubClass& source) : testClass(source)
{
for (auto& f: functionList)
f = rebind(f);
}
Working demo .
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.