簡體   English   中英

模板專業化與模板

[英]Template specialization with a template

我想在C ++ 11中定義以下函數:

// This is the general function that should
// never been instantiated
//
template <typename T>
T load(const std::string& filename) {
  return T{};
}

適用於各種類型。

我想將這個函數專門用於類型為std :: vector <S>(或任何模板化類)的類。 就像是 :

template <typename std::vector<S>>
std::vector<S> load(const std::string& filename) {
  // Implementation
}

這段代碼顯然不起作用。 但我怎么能這樣做?

謝謝你的幫助。

函數不能是部分專用的,但struct / class可以,所以將您的實現轉發給專用的struct:

template <typename T> struct load_helper;

template <typename T> struct load_helper<std::vector<T>>
{
    std::vector<T> operator ()(const std::string& filename) const
    {
        // Your implementation
    }
};

template <typename T>
T load(const std::string& filename) {
  return load_helper<T>{}(filename);
}

在C ++中,沒有函數模板部分特化 您想要做的是為函數模板定義重載 ,例如:

// warning: this will not work in your case
template<typename S>
std::vector<S> load(const std::string& filename);

但是,它不適用於您的情況,因為您不能重載僅更改其返回類型的函數。

暫無
暫無

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

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