免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1501 | 回复: 3
打印 上一主题 下一主题

[C++] c++适配器问题请教 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-10-16 13:23 |只看该作者 |倒序浏览
我看到一下代码,但是不知道怎么回事,怎么用,那位高手解释一下??

谢谢!!

/*
*        实现两个适配器
*/
#ifndef __SELPAIR_H__
#define __SELPAIR_H__

#include <utility>
#include <functional>

// select1st and select2nd are extensions: they are not part of the standard.
namespace std
{

#ifdef _WIN32

template <class _Pair>
struct _Select1st : public unary_function<_Pair, typename _Pair::first_type>
{
        const typename _Pair::first_type& operator()(const _Pair& __x) const
        {
                return __x.first;
        }
};

template <class _Pair>
struct _Select2nd : public unary_function<_Pair, typename _Pair::second_type>
{
        const typename _Pair::second_type& operator()(const _Pair& __x) const
        {
                return __x.second;
        }
};

#endif // _WIN32
template <class _Pair> struct select1st : public _Select1st<_Pair> {};
template <class _Pair> struct select2nd : public _Select2nd<_Pair> {};
};

#endif // __SELPAIR_H__

论坛徽章:
0
2 [报告]
发表于 2006-10-16 15:58 |只看该作者
这个是不是仿函数呀?
不过具体怎么调用呢?
哪位高手给举个例子?

谢谢!!

论坛徽章:
0
3 [报告]
发表于 2006-10-16 19:15 |只看该作者

  1. #include <iostream>
  2. #include <Pair.h>
  3. #include <Functional>
  4. #include <stdio.h>

  5. template <class _Pair>
  6. struct MySelect1st : public unary_function<_Pair, typename _Pair::first_type>
  7. {
  8.         const typename _Pair::first_type& operator()(const _Pair& __x) const
  9.         {
  10.                 return __x.first;
  11.         }
  12. };

  13. int main()
  14. {
  15.         pair<int, double> testPair(3, 10.0);
  16.         MySelect1st< pair<int, double> > Select1stOperator;
  17.         printf("%d\n", Select1stOperator(testPair));

  18.         return 0;
  19. }
复制代码


为了不跟标准的重复定义,我把这个仿函数的名字改了一下,这个仿函数的作用就是重载operator()函数,从而在调用的时候传入一个pair得到这个pari的first成员

论坛徽章:
0
4 [报告]
发表于 2006-10-17 08:38 |只看该作者
谢谢楼上的!!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP