2013-12-20 40 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