【发布时间】:2010-07-22 11:15:34
【问题描述】:
我对这门课有疑问。
目标是使主要功能正常工作。我们应该实现“And”函数对象,这样代码才能工作。我找不到我们的解决方案有什么问题。
(解决方案开始和结束在“main”函数之前的代码中用cmets标记)
你能帮忙吗?
谢谢
#include <iostream>
#include <algorithm>
using namespace std;
class NotNull
{
public:
bool operator()(const char* str) {return str != NULL;}
};
class BeginsWith
{
char c;
public:
BeginsWith(char c) : c(c) {}
bool operator()(const char* str) {return str[0] == c;}
};
class DividesBy {
int mod;
public:
DividesBy(int mod) : mod(mod) {}
bool operator()(int n) {return n%mod == 0;}
};
//***** This is where my sulotion starts ******
template <typename Function1, typename Function2, typename T>
class AndFunction
{
Function1 f1;
Function2 f2;
public:
AndFunction(Function1 g1, Function2 g2) : f1(g1), f2(g2) {}
bool operator()(T t)
{
return (f1(t) && f2(t));
}
};
template <typename Function1, typename Function2, typename T>
AndFunction <Function1, Function2, T>
bool And(Function1 f1, Function2 f2)
{
return AndFunction<Function1, Function2, T>(f1, f2);
}
//***** This is where my sulotion ends ******
int main(int argc, char** argv)
{
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char* strings[4] = {"aba", NULL, "air", "boom"};
cout << count_if(array,array+10,And(DividesBy(2),DividesBy(4))) << endl;
// prints 2, since 4 and 8 are the only numbers which can be divided by
// both 2 and 4.
cout << count_if(strings,strings+4,And(NotNull(),BeginsWith('a'))) <<endl;
// prints 2, since only "aba" and "air" are both not NULL and begin
// with the character 'a'.
return 0;
}
【问题讨论】:
-
究竟是什么不起作用?我觉得奇怪的是,您将 t 传递给 operator bool 中的函数。
-
一些注意事项: 1. Functors 通常继承自
std::unary_function和std::binary_function或定义 typedefsfirst_argument_type,second_argument_type,result_type以使其与例如兼容。 Boost.Functions。 2. 迭代器以外的类对象通常是通过const引用来传递的。 3.operator()通常是常量。 4. 字符文字是常量对象,不鼓励将它们转换为char*。 5. 函子NotNull、BeginsWith和DividesBy也可以是泛型的。
标签: c++ templates function-object