- 论坛徽章:
- 0
|
struct WidgetNameCompare:
public std::binary_function<Widget, Widget, bool>{
bool operator()(const Widget& lhs, const Widget& rhs) const;
};
在两种情况下,注意传给unary_function或binary_function的类型与传给仿函数类的operator()和从那里返回的
一样,虽然operator的返回类型作为最后一个实参被传递给unary_function或binary_function有一点古怪。
你可能注意到了MeetsThreshold是一个类,而WidgetNameCompare是一个结构。MeetsThreshold有内部状态
(它的阈值数据成员),而类是封装那些信息的合理方法。WidgetNameCompare没有状态,因此不需要任何
private的东西。所有东西都是public的仿函数类的作者经常把它们声明为struct而不是class,也许只因为可以避
免在基类和operator()函数前面输入“public”。把这样的仿函数声明为class还是struct纯粹是一个个人风格问
题。如果你仍然在精炼你的个人风格,想找一些仿效的对象,看看无状态STL自己的仿函数类(比如,
less<T>、plus<T>等)一般写为struct。再看看WidgetNameCompare:
struct WidgetNameCompare:
public std::binary_function<Widget, Widget, bool> {
bool operator()(cost Widget& lhs, const Widget& rhs) const;
}
虽然operator的实参类型是const Widget&,但传给binary_function的是Widget。一般来说,传给unary_function
或binary_function的非指针类型都去掉了const和引用。(不要问为什么。理由不很好也不很有趣。如果你真
的想知道,写一些没有去掉它们的程序,然后去解剖编译器诊断结果。如果完成了这步,你仍然对这个问题
感兴趣,访问boost.org(参见条款50)然后看看他们关于特性和函数对象适配器的工作。)
当operator()的参数是指针时这个规则变了。这里有一个和WidgetNameCompare相似的结构,但这个使用
Widget*指针:
struct PtrWidgetNameCompare:
public std::binary_function<const Widget*, const Widget*, bool> {
bool operator()(const Widget* lhs, const Widget* rhs) const;
};
在这里,传给binary_function的类型和operator()所带的类型一样。用于带有或返回指针的仿函数的一般规则
是传给unary_function或binary_function的类型是operator()带有或返回的类型。
不要忘记所有使用这些unary_function和binary_function基类基本理由的冗繁的文字。这些类提供函数对象适配 |
|