2013-12-20 35 views
0

有一個模板類,像下面選擇性覆蓋模板類的功能

template<typename K, typename V> 
class Db { 
public: 
    Db(const string& dbname, int flags = O_RDWR|O_CREAT); 
    ~Db(); 

    // return true on success, false on failure 
    bool SimpleRetrieve(const K&, V&) const; 

    bool Retrieve(const K&, V&) const; 

}; 


同時,希望有SimpleRetrieve(const K&, string &) const;不同的實現,我如何聲明這樣一個模板類?

試過類似下面,力編譯...

template<typename K, typename V> 
class Db { 
public: 
    Db(const string& dbname, int flags = O_RDWR|O_CREAT); 
    ~Db(); 

    // return true on success, false on failure 
    bool SimpleRetrieve(const K&, V&) const; 

    template<> 
    bool SimpleRetrieve(const K&, string&) const; 

    bool Retrieve(const K&, V&) const; 

}; 
+0

帶上不同的虛擬參數 –

+0

如果模板類型是** not **'std :: string',你是否還希望'SimpleRetrieve'的兩個重載都是「活動的」(即可調用的)?如果模板類型**是** std :: string,那麼應該使用哪個函數呢? –

回答

1

你不需要template<>有在這種情況下,2個重載。

但是,如果你想要模板類方法afaik,你不能這樣做,因爲在非命名空間範圍內不允許特化。

所以,這應該很好地工作:

template<typename K, typename V> 
class Db { 
    public: 
     Db(const string& dbname, int flags = O_RDWR|O_CREAT); 
     ~Db(); 

     // return true on success, false on failure 
     bool SimpleRetrieve(const K&, V&) const; 

     bool SimpleRetrieve(const K&, string&) const; 

     bool Retrieve(const K&, V&) const; 
}; 

但我不知道你是如何編譯器將使用這樣的過載,你應該看看std::enable_if

1

要添加更多的什麼我上面的海報說:

你不能有一個模板類部分專業成員函數,除非整個班級是部分專業。

換句話說,如果你是莊家對整個DB類偏特若V是一個字符串的概念OK,你可以這樣做

template<typename K> 
class DB<K, string>{ 
//rest of your stuff here 
} 

編輯:

隨着關於Joachim Pileborg,這是一個不需要你重新實現你的整個DB類的替代方案。我中省略了一些細節,但這個想法應該是清楚的:

template<typename K, typename V> 
class AbstractDb { 
public:  

    bool Retrieve(const K&, V&) const { std::cout << "Retrieve for K and V" << std::endl; return true; }; 

}; 


template<typename K, typename V> 
class Db: public AbstractDb<K, V>{ 
public: 
    bool SimpleRetrieve(const K&, const V&) const {std::cout << "Generic Db2 Simple Retrieve" << std::endl; return true;}; 

}; 

template<typename K> 
class Db<K, std::string> : public AbstractDb<K, std::string>{ 
public: 
    bool SimpleRetrieve(const K&, const std::string&) const {std::cout << "SPecialized Db2 Simple Retrieve" << std::endl; return true;}; 

}; 


int main() 
{ 
    Db2<int, int> db; 
    int a = 4, b = 5; 
    db.SimpleRetrieve(a,b); 
    db.Retrieve(a,b); 

    Db2<int, std::string> specdb; 

    std::string str = "abcd"; 
    std::string str2 = "abcd2"; 
    specdb.SimpleRetrieve(a, str); 
    specdb.Retrieve(a, str2);  
    return 0; 
} 

的輸出是:

Generic Db2 Simple Retrieve 
Retrieve for K and V 
SPecialized Db2 Simple Retrieve 
Retrieve for K and V 

你會把你的功能需要進行專門數據庫,和那些那不 - 在抽象DB中。

+0

爲了不必重新實現類中的每個方法,OP可以創建一個除SimpleRetreive函數外基本類,然後泛型類和特化類繼承基類。 –

+0

@divinas:如果我們從一個部分專門化的類開始,我可以擴展特定的函數來模板化兩個參數,有些事情就像首先定義一個部分模板類'template class Db {fun(K&,string & V; template fun(K &,V&);}' – Shashi

+0

我不是100%確定我正確理解你的問題 你可以在你的部分專門化類中有正常的模板化函數,它們的行爲就像正常的模板化函數。所以是的,你可以有一個模板化的功能,這將取決於一些模板參數,而不是該類的專業化的一部分,但它們將是不同的。 – divinas