以下面的例子为例: (请注意,该示例不起作用,但它应该足以说明我正在尝试做的事情)
class Point {
float x, y;
public:
float getX() const { return x; }
float getY() const { return y; }
};
class Polygon {
std::vector<Point> points;
std::vector<float> get(float (Point::*func)()const) {
std::vector<float> ret;
for(std::vector<Point>::iterator it = points.begin(); it != points.end(); it++) {
// call the passed function on the actual instance
ret.push_back(it->*func());
}
return ret;
}
public:
std::vector<float> getAllX() const {
return get(&Point::getX); // <- what to pass for getX
}
std::vector<float> getAllY() const {
return get(&Point::getY); // <- what to pass for getY
}
};
编辑:
问题是操作顺序;编译器要求在调用周围加上括号:
(it->*func)()
最佳答案
看起来您想使用“指向成员函数的指针”,它使用以下语法:
class Point {
float x, y;
public:
float getX() const { return x; }
float getY() const { return y; }
};
class Polygon {
std::vector<Point> points;
std::vector<float> get(float (Point::*func)()) { // !!! NEW SYNTAX - POINTER TO MEMBER
std::vector<float> ret;
for(std::vector<Point>::iterator it = points.begin(); it != points.end(); it++) {
// call the passed function on the actual instance
ret.push_back((it->*func)()); // !!! ADDED PARENTHESES
}
return ret;
}
public:
std::vector<float> getAllX() const {
return get(&Point::getX); // !!! POINTER TO MEMBER
}
std::vector<float> getAllY() const {
return get(&Point::getY); // !!! POINTER TO MEMBER
}
};
免责声明:未经测试。
另外,您可能想查看 <functional>
图书馆 C++11
;它非常适合这样的事情。
这就是我个人可能处理这种情况的方式:
#include <functional>
#include <vector>
#include <algorithm>
class Point {
float x, y;
public:
float getX() const { return x; }
float getY() const { return y; }
};
class Polygon {
std::vector<Point> points;
std::vector<float> get(std::function<float(const Point&)> func) const {
std::vector<float> ret(points.size());
std::transform(points.begin(), points.end(), ret.begin(), func);
return ret;
}
public:
std::vector<float> getAllX() const {
return get(std::mem_fn(&Point::getX));
}
std::vector<float> getAllY() const {
return get(std::mem_fn(&Point::getY));
}
};
免责声明:已编译,但未经测试。
关于c++ - 在事先不知道实例的情况下使用函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16020366/