这个问题源于我在这里问过的一个问题。我不能使用任何外部库或 C++ 11 规范。这意味着我不能使用 std::bind、std::function、boost::bind、boost::function 等。我必须自己编写。问题如下:
考虑代码:
编辑
这是一个完整的程序,可按要求显示问题:
#include <map>
#include <iostream>
class Command {
public:
virtual void executeCommand() = 0;
};
class Functor {
public:
virtual Command * operator()()=0;
};
template <class T> class Function : public Functor {
private:
Command * (T::*fptr);
T* obj;
public:
Function(T* obj, Command * (T::*fptr)()):obj(obj),
fptr(fptr) {}
virtual Command * operator()(){
(*obj.*fptr)();
}
};
class Addition:public Command {
public:
virtual void executeCommand(){
int x;
int y;
x + y;
}
};
class CommandFactory {
public:
virtual Addition * createAdditionCommand() = 0;
};
class StackCommandFactory: public CommandFactory {
private:
Addition * add;
public:
StackCommandFactory():add(new Addition()) {}
virtual Addition * createAdditionCommand(){
return add;
}
};
void Foo(CommandFactory & fact) {
Function<CommandFactory> bar(&fact,&CommandFactory::createAdditionCommand);
}
int main() {
StackCommandFactory fact;
Foo(fact);
return 0;
}
它给出的错误是"no instance of constructor "Function<T>::Function [with T=CommandFactory] matches the argument list, argument types are: (CommandFactory *, Addition * (CommandFactory::*)())
我认为它在抱怨,因为我将它传递给派生类型。我必须使用对抽象类的指针/引用,因为fact
以后可能不是 StackCommandFactory。
我不能说:
void Foo(CommandFactory & fact){
Function<CommandFactory> spf(&fact,&fact.createAdditionCommand); //error C2276
}
因为那时我收到错误 C2276 说(在我链接到的问题中)'&' : illegal operation on bound member function expression.
所以明确我的问题是:“我如何初始化这个函子对象,以便我可以将它与上述接口一起使用?”