C++模板中的函数对象

在C++模板类map中一个参数为Compare类型,该类型为一个比较函数,其完整定义如下:

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

函数作为类进行传递,该类采用了重载操作符()来实现函数指针到类的转变。在实际中也可以仿照此风格写自己的类。

 1 template <typename Key, typename Value, class Hash >
 2 class A     {
 3     Hash hash_fn;
 4 public:
 5     A():hash_fn(Hash()) {
 6 
 7     }
 8 
 9     size_t hashCode(Key key) { return hash_fn(key);}
10 
11 };

第三个参数Hash为函数对象,该对象通过重载操作符()来实现,其一个字符串类型的Key定义如下:

1 struct str_hash {
2     size_t operator()(const std::string& str) const
3     {
4         return 0;
5     }
6 };

当调用hash_fn(key)函数时,该重载函数被调用,这样就实现了转换。由于C++标准库中包含有大量此类型风格的类,我们就可以通过默认参数来调用标准类,这样上面的模板类A就可以定义如下:

template <typename Key, typename Value, class Hash = std::hash<Key>>

测试程序如下:

 1 int main(int argc, char *argv[]) {
 2     
 3     A<std::string , int, str_hash> a;
 4     std::cout << "hashCode:" << a.hashCode("abc") << std::endl;
 5 
 6     A<std::string,int,std::hash<std::string>> h;
 7     std::cout << h.hashCode("abc") << std::endl;
 8 
 9     A<std::string,int> h2;
10     std::cout << h.hashCode("abc") << std::endl;
11     
12     return 0;
13 }

测试结果如下:

1 functiontem
2 hashCode:0
3 3350977461
4 3350977461

posted on 2015-06-02 09:17  kkford  阅读(507)  评论(0编辑  收藏  举报

导航