我想创建一个“泛型”priority_queue,它是A类的成员,这样我就不需要在编译时指定比较器仿函数类。我将在运行时选择比较器funtor。我怎样才能实现这个目标?下面是我的用例的简化示例。
我无法使用任何C ++ 11功能。
class A{
private:
priority_queue<T, vector<T>, ?> *pq;
public:
A(string );
~A();
};
A::A(string s) {
if(s == "1")
pq = new priority_queue<T, vector<T>, Mycomparator1>;
else (s == "2")
pq = new priority_queue<T, vector<T>, Mycomparator2>;
}
A::~A(){
delete pq;
}
struct Mycomparator1 {
bool operator()(const T&a, const T&b){
return a.x > b.x;
}
};
struct Mycomparator2 {
bool operator()(const T&a, const T&b){
return a.y > b.y
}
};
int main(){
string s(argv[1]);
A(s);
}
答案 0 :(得分:1)
您无法在运行时确定比较器的类型。但是你能做的就是让比较器的行为取决于运行时值。一个适合您案例的简单示例如下:
struct MyComparator3 {
bool compare_x;
bool operator()(const T& a, const T& b) const {
if (compare_x)
return a.x > b.x;
else
return a.y > b.y;
}
};
另一个更通用的可能性是使用像std::function<bool(T,T)>
这样的东西,或者(因为你说你不能使用C ++ 11)boost::function
。