2012-01-09 125 views
0

還有就是我的程序,它說明了可以用作分揀的STL容器實例作謂語模板:STL:指針關聯分類容器:排序謂詞模板

#include <iostream> 
#include <set> 
#include <iterator> 
#include <algorithm> 
#include <functional> 
#include <string> 

using namespace std; 

template<typename T, template <typename> class comp = std::less> struct ComparePtr: public binary_function<T const *, T const *, bool> { 
    bool operator()(T const *lhs, T const *rhs) const { 
    comp<T> cmp; 
    return (cmp(*lhs, *rhs)); 
    } 
}; 

int wmain() { 
    string sa[] = {"Programmer", "Tester", "Manager", "Customer"}; 
    set<string *, ComparePtr<string>> ssp; 
    for (int i(0) ; i < sizeof sa/sizeof sa[0] ; ++i) 
    ssp.insert(sa + i); 

    for_each(ssp.begin(), ssp.end(), [](string *s){ cout << s->c_str() << endl; }); 

    return 0; 
} 

請,專注於謂語:這是正確寫入? 是否很好實例化comp?有沒有一種方法可以不實例化comp謂詞?

回答

3

爲什麼要使用模板模板而不僅僅是在通用的二進制比較器周圍添加一個簡單的包裝?

template<typename P> 
struct PointerPred { 
    P p; 
    template<typename T> 
    bool operator()(const T& x, const T& y) { return p(*x, *y); } 
}; 

Boost Pointer Containers也可以使這更容易。

Ildjarn展示瞭如何正確地執行你的仿函數:

template<template<typename> class comp = std::less> 
struct ComparePtr { 
    template<typename T> 
    bool operator()(T const *lhs, T const *rhs) const { 
    return comp<T>()(*lhs, *rhs); 
    } 
}; 

這種方式沒有必要去指定的參數的類型。

編輯:在我的代碼中曾經有std::forward和右值引用,這絕對沒有意義。

+1

「*爲什麼要使用模板模板*」因爲它不需要人們說出'T'的類型,而您的方法卻是這樣。 C.F. http://ideone.com/jvTnm其中所需要的只是'ComparePtr <>',沒有指定其他內容。 – ildjarn 2012-01-09 23:35:12

+1

@ildjarn有道理。儘管OPs代碼並非如此,所以我從來沒有考慮過它。你能把它作爲答案發布嗎?之後我會刪除我的答案。 – pmr 2012-01-09 23:43:45

+1

我很好,你編輯你的答案,任何方式都沒有什麼大不了的。 : - ] – ildjarn 2012-01-09 23:50:39