获取函数指针和类指针的函数
a function that gets a function pointer and a class pointer?
我想在一个名为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});
当然,您可以使用模板使其更加通用。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针