有一个简单的POD数据类型,如
struct Item {
int value1;
double value2;
bool value3;
}
现在我想编写不同的count函数,就像使用以下代码(或某些std方法)一样:
typedef bool Selector(const Item& i);
int count(const vector<Item>& items, Selector f) {
int sum = 0;
BOOST_FOREACH(const Item& i, items) {
if(f(i)) {
sum++;
}
}
return sum;
}
与f
例如
bool someSimpleSelector(const Item& i) {
return i.value1 > 0; // quite simple criterion
}
但是在这种方法中,编译器无法内联函数调用,因此不会内联我的(普通)选择代码。
我的问题是:是否有可能以某种方式实现上述代码,编译器可以内联我的选择代码,但是没有一次又一次地实现整个计数功能(例如通过使用模板)? / p>
答案 0 :(得分:2)
答案 1 :(得分:1)
用模板参数替换typedef
,以允许通用仿函数:
template <typename Selector>
int count(const vector<Item>& items, const Selector &f)
然后用函数对象替换函数:
struct someSimpleSelector
{
bool operator()(const Item& i) const { return i.value1 > 0; }
};
您应该通过合适的编译器优化设置找到内联版本。
顺便说一下,可以使用std::count_if()
来解决这个特殊问题。