2012-05-11 79 views
0

我要定義名稱比較,這需要引用以及 爲指針模板化的仿相同的功能。我想使用它作爲一個普通的find_if元素的容器以及指針的容器(不幸的是,ptr_vector之類不是一個選項)。如何定義一個基準參數模板函數和指針參數

迄今爲止發現的最佳解決方案如下。

template <typename U> 
class by_name{ 
    public: 
    by_name(U const& pName):mName(pName) {} 

    template <class T> 
    typename boost::disable_if_c<boost::is_pointer<T>::value, bool>::type 
    operator()(T const& pX){ return pX.getName()== mName;} 

    template <class T> 
    typename boost::enable_if_c<boost::is_pointer<T>::value, bool>::type 
    operator()(T pX){ return pX->getName()== mName;} 

private: 
    U mName; 
}; 

對於不知道enable_if的人來說,這看起來相當醜陋,很難理解。 有沒有一種更簡單的方法來編寫這樣一個函數,並且使用指針和參考?

回答

3

它可以是簡單的:

template <class T> 
bool operator()(T const& rX) const { return rX.getName() == mName; } 

template <class T> 
bool operator()(T* const pX) const { return pX->getName() == mName; } 
+2

大概指針的版本是一樣'const'明智的,所以我們會想'T const的*'作爲參數。更好的是,我們可以根據參考版本來實現它:'return(* this)(* pX);'。 –

1

做實現的getName成員函數的類返回任何東西比的std :: string別的嗎?如果沒有,您可以擺脫一個模板參數。

這是我會如何實現的函子:

class by_name 
{ 
    public: 
    by_name(const std::string& name) : 
     Name(name) {} 

    template <class T> 
    bool operator()(T const& pX) const 
    { 
     return pX.getName() == Name; 
    } 

    template <class T> 
    bool operator()(T* pX) const 
    { 
     if (!pX) // how do you handle a null ptr? 
     return false; 
     (*this)(*pX); // @Luc Danton 
    } 

    private: 
    std::string Name; 
}; 

如果指針版本爲

bool operator(T const* pX) const {} 

GCC由於某種原因,執行選擇實例

bool operator(T const& pX) const with [T = A*] 

的仿函數已經被編譯並用gcc 4.6.1進行了測試。

+0

好主意,但我也有QString以及在系統中處理這兩種字符串類型 – Martin

相關問題