2009-11-09 113 views
8

如何以非內聯方式爲專業模板提供額外的成員函數? 即C++模板專門化提供額外的成員函數?

template<typename T> 
class sets 
{ 
    void insert(const int& key, const T& val); 
}; 
template<> 
class sets<bool> 
{ 
    void insert(const int& key, const bool& val); 
    void insert(const int& key){ insert(key, true); }; 
}; 

但是,當我寫sets<bool>::insert(const int& key)作爲

template<> 
class sets<bool> 
{ 
    void insert(const int& key, const bool& val); 
    void insert(const int& key); 
}; 
template<> 
void sets<bool>::insert(const int& key) 
{ 
    insert(key, true); 
} 

GCC抱怨:

模板id爲「無效 ip_set '插入<>' ::插入(const int的&)' 不匹配任何模板聲明

回答

4

這是因爲它不是你的模板的功能,所以不要使用「模板<>」。

void sets<bool>::insert(const int& key) 
{ 
    insert(key, true); 
} 

我的系統FC9 x86_64的:它刪除如下 「模板<>」 後,對我的作品。

整個代碼:

template<typename T> 
class sets 
{ 
public: 
    void insert(const int& key, const T& val); 
}; 

template<> 
class sets<bool> 
{ 
public: 
    void insert(const int& key, const bool& val) {} 
    void insert(const int& key); 
}; 

void sets<bool>::insert(const int& key) 
{ 
    insert(key, true); 
} 

int main(int argc, char **argv) 
{ 
     sets<bool> ip_sets; 
     int key = 10; 
     ip_sets.insert(key); 
     return 0; 
} 
9

再說什麼Effo說,如果你想在專業化添加額外的功能,你應該將常用功能爲基本模板類。例如:

template<typename T> 
class Base 
{ 
public: 
    void insert(const int& key, const T& val) 
    { map_.insert(std::make_pair(key, val)); } 
private: 
    std::map<int, T> map_; 
}; 

template<typename T> 
class Wrapper : public Base<T> {}; 

template<> 
class Wrapper<bool> : public Base<bool> 
{ 
public: 
    using Base<bool>::insert; 
    void insert(const int& key); 
}; 

void Wrapper<bool>::insert(const int& key) 
{ insert(key, true); }