【发布时间】:2011-05-26 12:28:28
【问题描述】:
我有一些类从基类继承的代码。
那个基类有一个函数,当运行时,它应该调用要由子类实现的函数。也就是说,一般算法对所有孩子都是一样的,但步骤的实现应该有所不同。
template<class T>
class Foo
{
public:
Foo(T y):y(y) { for(int i; i < 10; ++i) x.push_back(i); };
protected:
virtual bool IsOk(T, int)=0;
void Run()
{
vector<int>::iterator it, bound;
for(int i; i < 10; ++i)
{
cout << "step " << i << endl;
bound = partition(x.begin(), x.end(), bind2nd(mem_fun_ref(&Foo<T>::IsOk), i));
for (it=x.begin(); it!=bound; ++it)
cout << " " << *it;
};
};
private:
vector<int>x;
T y;
};
class Bar : public Foo<int>
{
public:
Bar():Foo<int>(50){this->Run();};
bool IsOk(int x , int y) {return x == y;}
};
但是,当我这样做时,我收到以下错误消息:
no matching function for call to 'mem_fun_ref(bool (Foo<int>::*)(int, int))'
谁能提供一些关于我在做什么的见解?
【问题讨论】:
-
'mem_fun_ref(bool (Foo<int>::*)(int, int))的定义在哪里,你能告诉我们吗? -
@Als:
mem_fun_ref是标准库函数。 -
@Space:是的,刚刚检查过!我的错。
-
您所描述的(主函数调用虚方法,后代重写以自定义细节)被称为 模板方法模式,尽管在 C++ 上下文中,名称可能有点令人困惑,因为它实际上并不引用 C++ 模板。
标签: c++ inheritance binding virtual-functions overriding