技术宅和经济盲

Thursday, February 03, 2011

好累的C++

不知道是我太久没写了,还是coding style和C++的指针传递太危险了,编译和lint一直有问题。写程序花了2小时,让它编译通过花了6个小时,恐怕有重新学习C++的危险了。

下面举个例子:

hash_map<string, string=""> properties;
...
for (hash_map<string, string="">::const_iterator
    ii = properties.begin(); ii != properties.end(); ++ii) {
  LOG(INFO) << (ii-&gt;first) << " = " << (ii-&gt;second) << std:endl;
}

这不是一个很简单的code吗,结果死活编译不过去!爬到源码堆里一看,原来g++ 3.4 是这么定义的:

namespace __gnu_cxx {

template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
    class _EqualKey = equal_to<_Key>, class _Alloc = allocator<_Tp> >
class hash_map;

也就是说,你写一个hash_map<string, string>啥的的话,它回去lookup下面三个函数对象(是不是这个名字阿?):
struct hash<string> {  // just for simplication, in STL, it is basic_string
  size_t operator()(string s) const {...}
};
struct equal_to<string> {...};
struct allocator<string> {...};


然后我看了一下在hash_fun.h里的定义,就悲剧了!原来只有hash<const char *>。

所以,同学们,写C++的话,不会看源代码,大约只能等死了。而且,熟悉它的话,恐怕要花点时间,譬如说半年。当然,现在有些库已经挺好用的了,特别是boost。所以,你还是很有机会在很熟悉的情况下用的挺好的的。

至于我,我觉着language应该需要有些进步了,否则真的太浪费engineer的时间了。特别是好多C++ coding style方面的限制,真的就是用来防止函数副作用的而已。但是已经搞得写code和读code都不是那么方便了。

写code,应该和写文章一样让人有赏心悦目的感觉!

0 Comments:

Post a Comment

<< Home