有选择地覆盖模板化类的函数
Selectively override functions of templated class
有一个模板类,如下所示
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;
};
在这种情况下,您不需要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。
为了补充我上面的海报所说的话:
模板类中不能具有部分专用的成员函数,除非整个类是部分专用的。
换句话说,如果你同意在 V 是一个字符串的情况下对整个数据库类进行部分特化的概念,你可以做类似的事情
template<typename K>
class DB<K, string>{
//rest of your stuff here
}
编辑:
关于Joachim Pileborg,这里有一个替代方案,不需要你重新实现整个数据库类。我省略了一些细节,但这个想法应该很清楚:
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的函数和不需要的函数放在抽象数据库中。
相关文章:
- Fmod 函数清楚地输出一个预期的双精度值,但 if(fmod == 预期的双精度值)的计算结果不是 true
- 有选择地禁用第三方库的C++核心准则检查器
- 有选择地禁用库中的死代码消除
- C++,有选择地应用模板模式来发挥作用
- 使用 SFINAE 有选择地实例化模板的成员函数
- Arduino函数无缘无故地更改参数
- OpenCL 内置函数选择
- 有选择地隐藏类成员的成员
- 通过构造函数错误地播种梅森扭曲
- 编译时构造函数选择
- 内联函数选择条件
- c - 函数选择显示读取后stdin中有数据
- Clang 和 GCC 在使用大括号表示法和initializer_list时在构造函数选择上存在分歧
- 有选择地启用一个并行区域内的OpenMP进行循环
- 有选择地对向量 c++ 进行排序
- 有选择地替换 C++ 中 std::string 中的 (") 双引号
- 我可以在代码库中有选择地禁用RTTI以减少二进制尺寸
- 如何有选择地从缓冲区读取数据
- 有选择地覆盖模板化类的函数
- 有选择地内联函数(用于调试目的)