配接器(adapter)
时间:2023-04-26 14:07:00
适配器:用于修改容器、仿函数或迭代接口的东西。STL 提供的 queue 和 stack,虽然它看起来像一个容器,但它只能被视为一个容器适配器,因为它们的底部完全借助 deque,所有的操作都是底层的 deque 供应。改变 functor 接口者,叫 function adapter等。
适配器(adapter) 在 STL 在组件的灵活组合应用功能上,扮演转换器的角色。也是一种设计模式(适配器模式)。
用于容器,container adapterSTL 两个容器 queue 和 stack,它们修饰 deque 形成的接口。
应用于迭代器,iterator adapterSTL 为迭代器提供了许多适配器。
用于仿函数,function adapter。
代码举例
count_if第三个参数是仿函数,我们可以看到源代码只接受一个参数
template <class InputIterator, class Predicate, class Size> void count_if(InputIterator first, InputIterator last, Predicate pred, Size& n) {
for ( ; first != last; first) if (pred(*first)) n; }
然后我们看看less有两个入参,我们想使用它less这个仿函数作为count_if第三个参数。所以我们需要适应它
// 小于 template <class T> struct less : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const {
return x < y; } };
我们可以自己写配接器
class Foo {
public: bool operator()(int i) {
return less<
int
>
(
)
(i
,
3
)
;
// 小于3的数字
}
}
;
int
main
(
)
{
std
::vector
<
int
> v
=
{
1
,
2
,
3
,
4
}
; cout
<<
count_if
(v
.
begin
(
)
, v
.
end
(
)
,
Foo
(
)
)
<< endl
;
// 输出 2
return
0
;
}
接下来我们使用STL中的配接器bind2nd
bind2nd(绑定第二个参数)
template <class Operation>
class binder2nd
: public unary_function<typename Operation::first_argument_type, typename Operation::result_type> {
protected:
Operation op;
typename Operation::second_argument_type value;
public:
binder2nd(const Operation& x,
const typename Operation::second_argument_type& y)
: op(x), value(y) {
}
typename Operation::result_type
operator()(const typename Operation::first_argument_type& x) const {
return op(x, value);
}
};
template <class Operation, class T>
inline binder2nd<Operation> bind2nd(const Operation& op, const T& x) {
typedef typename Operation::second_argument_type arg2_type;
return binder2nd<Operation>(op, arg2_type(x));
}
测试用例
int main()
{
std::vector<int> v = {
1, 2, 3, 4};
cout << count_if(v.begin(), v.end(), bind2nd(less<int>(), 3)) << endl; // 输出 2
return 0;
}
总结
adapter:将一个class接口转换为另一个class接口,使原本因接口不兼容而不能合作的classes,可以一起运作。