簡體   English   中英

使用模板專業化添加方法

[英]Adding methods with template specialization

我有一個稱為Map的哈希表容器,使用以下方法:

Value Map<Key, Value>::valueFor(const Key& key);

不幸的是,最常用的情況是Key = std::string ,在這里我們通常使用字符串文字來調用該方法,例如:

const Value v = map.valueFor("my_key");

我們放松了幾個創建std::string周期。 因此,我想添加一個重載

Value Map<std::string, Value>::valueFor(const char* key);

Key = std::string 我確信編譯器甚至可以在編譯時使用這種簽名來計算哈希,這也將有助於加快處理速度。

有沒有一種方法可以在C++11做到而無需模板專門化整個Map類並重寫所有方法?

您可以添加另一個重載valueFor(char const * key) 如果Key不是std::string那么您可能還想通過SFINAE禁用此重載。

#include <iostream>
#include <string>
#include <type_traits>

template < typename Key, typename Value >
struct Map
{
    Value valueFor(Key const& key)
    {
        std::cout << "valueFor(const Key& key)\n";
        return Value{};
    }

    template < typename _Key = Key,
               typename = typename std::enable_if< std::is_same < _Key, std::string >::value >::type >
    Value valueFor(char const * key)
    {
        std::cout << "valueFor(char const * key)\n";
        return Value{};
    }
};

int main()
{
    Map<std::string, int> map;
    int v = map.valueFor("my_key");

    Map<int, int> other_map;
  //int v = other_map.valueFor("my_key"); // BOOM!
}

只是削弱您的類型要求。 只要表達式hash<Key>(arg)有效,您的valueFor (無需)關心參數的類型。

因此,您可以將valueFor其參數類型的模板,並僅對哈希函數和關鍵比較器(如有必要)進行專門化處理。

例如。 (未經測試,為簡潔起見,使用C ++ 17 string_view

template <typename K>
struct Hasher
{
  static size_t hash(K const &k) { return std::hash<K>()(k); }
};
template <>
struct Hasher<std::string>
{
  static size_t hash(std::string const &s) {
    return std::hash<std::string>()(s);
  }
  static size_t hash(std::string_view const &sv) {
    return std::hash<std::string_view>()(sv);
  }
  static size_t hash(const char *cstr) {
    return std::hash<std::string_view>()({cstr});
  }
};

template <typename Key, typename Value>
template <typename KeyArg>
Value Map<Key,Value>::valueFor(KeyArg&& arg)
{
    auto hash = Hasher<Key>::hash(std::forward<KeyArg>(arg));
    // ...
}

暫無
暫無

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

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