簡體   English   中英

將類型作為函數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被定義為采用該類型?

編譯器:單聲道

您需要使用模板來執行此操作。 是一個例子。

#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的迭代器來遍歷它的項目?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM