获取函数指针和类指针的函数

a function that gets a function pointer and a class pointer?

本文关键字:函数 指针 获取      更新时间:2023-10-16

我想在一个名为Map的类中制作MapIf函数。 MapIf将像这样称呼:

void addThree(int& n) {
    n += 3;
}
class startsWith {
    char val;
public:
    startsWith(char v) : val(v) {};
    bool operator()(const std::string& str) {
        return str.length() && char(str[0]) == val;
    }
};
int main(){
...
    startsWith startWithB('B');
    Map<std::string, int> msi;
    MapIf(msi, startWithB, addThree);
    return 0;
}

什么是MapIf宣言?

void MapIf(const Map& map, class condition, void (*function)(ValueType));

可以吗?

以下内容应该与您的原型相匹配。

template <typename Key, typename Value, typename Condition>
void MapIf(const Map<Key, Value>& map, Condition condition, void (*function)(Value&));

宁愿

void MapIf(const Map& map, startsWith condition, void (*addThree)(int));

看起来你想要有多个条件,所有条件都是函数对象。我可以建议你使用std::function作为条件。在这种情况下,您可以使用此类和其他类以及其他函数甚至 lambda;

MapIf(Map<std::string, int>& map, std::function<bool(const std::string&)> condition, std::function<void(int&)> callback);

在这种情况下,您可以通过以下方式调用此函数:

MapIf(msi, startWithB, addThree);
MapIf(msi, [](const string& str)->bool{return str.length() % 2 = 0}, addThree);
MapIf(msi, startWithA, [](int& val){val-=2});

当然,您可以使用模板使其更加通用。