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

时间:2014-01-13 12:09:34

标签: c++ class function-pointers

我想在名为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));

这样可以吗?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

相反

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

答案 2 :(得分:0)

看起来你想拥有多个条件,所有条件都是function objects。 我建议你使用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});

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

相关问题