Chinaunix首页 | 论坛 | 博客
  • 博客访问: 932427
  • 博文数量: 158
  • 博客积分: 4380
  • 博客等级: 上校
  • 技术积分: 2367
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-21 10:45
文章分类

全部博文(158)

文章存档

2012年(158)

我的朋友

分类: C/C++

2012-11-20 11:30:09

// 用到了typeof,只能在gcc上编译通过
struct foo
{
    int a;
    float b;
};

template
bool _myless( const foo& lhs, const foo& rhs )
{
    return lhs.*M < rhs.*M;
}
#define myless(a) _myless

int main()
{
    foo a, b;

    _myless( a, b );
    _myless( a, b );

    myless(foo::a)( a, b );
    myless(foo::b)( a, b );
}

// 失败的尝试
struct foo
{
    int a;
    float b;
};

template
bool myless( foo lhs, foo rhs )
{
    return lhs.*M < rhs.*M;
}

template
bool (& bar( T M ) )( foo lhs, foo rhs )
{
    return myless; // M是运行时给定,而myless必须在编译时确定
}

// 改进后的代码
struct foo
{
    int a;
    float b;
};

template
class myless_
{
public:
    myless_( T M ) : M_(M)
    {
    }
    bool operator()( const foo& lhs, const foo& rhs ) const
    {
        return lhs.*M_ < rhs.*M_;
    }
private:
    T M_;
};

template
myless_ myless( T M )
{
    return myless_(M);
}

#include
int main()
{
    using namespace std;

    foo a = { 1, 1.0f };
    foo b = { 2, 2.0f };
   
    cout << boolalpha << myless(&foo::a)( a, b ) << endl; // true
    cout << boolalpha << myless(&foo::a)( b, a ) << endl; // false

    cout << boolalpha << myless(&foo::b)( a, b ) << endl; // true
    cout << boolalpha << myless(&foo::b)( b, a ) << endl; // false
}

阅读(787) | 评论(3) | 转发(0) |
给主人留下些什么吧!~~

网友评论2012-11-20 11:31:03

wq
这样啊,那还不如用boost::lambda.
find(mapx.begin(), mapx.end(), bind(&map<XX>::value_type::second, _1) == x)
查找map里value为x的对象.

网友评论2012-11-20 11:30:55

wmuu
template<typename T,typename M>
bool less_2 (T& lhs, T&rhs, M m){
return lhs.*m < rhs.*m;
}

网友评论2012-11-20 11:30:47

wdscxsj
斧正不敢,这个是按你的意思写的。为了体现成员变量指针是编译时常量,硬把它提到template参数里去,似乎把代码复杂化了。在VC7.1下编译通过。

#include <iostream>

struct C
{
    int i;
    double d;
};

template<typename PDM, PDM pdm, typename T>
bool myless(T const& t1, T const& t2)
{
    return t1.*pdm < t2.*pdm;
}

int main()
{
    using names