std::mem_fun和编译器

std::mem_fun和编译器
 

Exceptional C++ Style一书第四条阐述了std::mem_fun的相关问题,尝试了下述的代码。

 
int main()
{
 
    int a1[] = {2,1,5,6,4};
    int a2[] = {11,4,67,3,14};
    list<int> s1(a1,a1+5);
    list<int> s2(a2,a2+5);
 
    // Build a list of lists
    list<list<int>* > l;
    l.insert(l.begin(), &s1);
    l.insert(l.begin(), &s2);
 
    // Sort each list in the list  

    for_each(l.begin(), l.end(), mem_fun(&list<int>::sort));

 

    copy(s1.begin(), s1.end(), ostream_iterator<int>(cout, " "));

    cout << "/n";

    copy(s2.begin(), s2.end(), ostream_iterator<int>(cout, " "));

   
    system("pause");
    return 0;
}
 
上述代码在 Dev-C++ 4.9.9 .2 )中编译,在红色的一行出现下述编译错误:

no matching function for call to `mem_fun(<unknown type>)'

 

这个例子是从roguewaveSTL文档中直接摘出来的例子,居然出错,百思不得其解。后来将这段代码放到Visual Stdio 2005 beta2中进行编译,顺利通过编译,运行也正确。

 
后来再仔细看了书里的叙述:某些流行的编译器不能正确推导出模板参数,需要手工提供模板参数。于是按书中给的一个例子将上面红色的代码改为:

for_each(l.begin(), l.end(), mem_fun<void, std::list<int, std::allocator<int> > >(&list<int>::sort));

 
结果成功通过编译!看来果真如作者( Herb Sutter )所讲,是编译器的问题。查看了一下这个版本的 Dev-C++ 所用的编译器:
 
 

D:/Dev/Dev-Cpp/bin>g++ --version

g++ (GCC) 3.4.2 (mingw-special)

Copyright (C) 2004 Free Software Foundation, Inc.

This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

 
2004 年的编译器,在这个特性上支持的还不是很好,不知道最新的 GCC 编译器如何了?

注:利用春节假期,看了一点C++的书,尝试了一些代码,贴出来和大家共享。这是第一篇。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值