c++ - 在事先不知道实例的情况下使用函数指针

标签 c++ function-pointers

以下面的例子为例: (请注意,该示例不起作用,但它应该足以说明我正在尝试做的事情)

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/

相关文章:

c++ - 直观地解释指针及其意义?

c++ - 二维数组重载

c++ - Winelib 能否将 DLL 直接链接到 ELF 可执行文件?

c++ - 存储函数指针的正确语法

c++ - 如何将函数指针作为参数传递给重载的成员函数

c++ - 使用指向独立函数的指针调用 std::thread

c++ - 为什么 OpenCL 在 cpp 中使用 0xdeadbeef?

c++ - 如何初始化具有 const 变量的结构数组

c++ - 如何找到两张 map 的差异?

c - 指向 "undefined"函数的函数指针