将类型作为函数C++的参数
Take a type as a parameter to a function C++
我有以下代码,它在C++中实现了一个简单的Hash/Dict
Hash.h
using namespace std;
#include <string>
#include <vector>
class Hash
{
private:
vector<const char*> key_vector;
vector<const char*> value_vector;
public:
void set_attribute(const char*, const char*);
string get_attribute(const char*);
};
Hash.cpp
using namespace std;
#include "Hash.h"
void Hash::set_attribute(const char* key, const char* value)
{
key_vector.push_back(key);
value_vector.push_back(value);
}
string Hash::get_attribute(const char* key)
{
for (int i = 0; i < key_vector.size(); i++)
{
if (key_vector[i] == key)
{
return value_vector[i];
}
}
}
目前,它唯一可以作为键/值的类型是const char*
,但我想扩展它,使其可以采用任何类型(显然每个哈希只有一个类型)。我想通过定义一个以类型为参数的构造函数来实现这一点,但我完全不知道在这种情况下如何做到这一点。我该如何做到这一点,以及如何实现它,以便将set_attribute定义为采用该类型?
编译器:Mono
您需要使用模板来完成此操作。下面是一个例子。
#ifndef HASH_INCLUDED_H
#define HASH_INCLUDED_H
#include <string>
#include <vector>
template <typename T>
class Hash
{
private:
std::vector<const T*> key_vector;
std::vector<const T*> value_vector;
public:
void set_attribute(const T*, const T*)
{
/* you need to add definition in your header file for templates */
}
T* get_attribute(const T*)
{
/* you need to add definition in your header file for templates */
}
};
#endif
请注意,我已经删除了using namespace std;
,因为它完全删除了名称空间的全部意义,尤其是在头文件中。
编辑:还有,你为什么不使用std::vector的迭代器来循环遍历它的项呢?
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用