(C++)我有很多Entry类,并且获得了包含Entry处理逻辑的BaseProcessor接口。 (见下面的代码)使用函数指针作为模板参数
该条目不提供运营商<()。 BaseProcessor提供了一个指向特定BaseProcessor实现的less(Entry,Entry)函数的指针。
我可以使用函数指针来比较我的程序中的Entry实例。然而,我需要创建std :: set(或std :: map或其他使用less())的Entry类。我试图使用std :: binary_function派生类将它传递给std :: set,但它看起来像我不能将函数指针值传递给模板。
我该怎么做?用C++ 03可以吗?
谢谢。
struct Entry
{
// ...
private:
bool operator< (const Entry &) const; // Should be defined by BaseProcessor.
};
typedef bool (*LessFunc)(const Entry &, const Entry &);
class BaseProcessor
{
public:
// ...
virtual LessFunc getLessFunc() const = 0;
};
// ...
BaseProcessor *processor = getProcessor();
LessFunc lessfunc = processor->getLessFunc();
Entry e1;
Entry e2;
bool isLess = lessfunc(e1, e2); // OK
typedef std::set<Entry, ???> EntrySetImpl; // how to use lessfunc here?
EntrySetImpl entries;
是的,它的工作原理。万分感谢。 – Rom098 2010-10-22 11:50:15
但是...它看起来像没有办法使用函数指针值作为非类型模板参数。对?像“template class Comparator {...}” –
Rom098
2010-10-22 11:54:34
@Roman - 你也可以这样做,对于你写的类,但是'set'不能像那样工作。但是,您指定为模板参数的'LessFunc'必须是编译时常量(例如,它不能是调用函数的结果)。 – Doug 2010-10-22 11:59:39