将类型作为函数C++的参数

Take a type as a parameter to a function C++

本文关键字:C++ 参数 函数 类型      更新时间:2023-10-16

我有以下代码,它在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的迭代器来循环遍历它的项呢?