使用模板的模板专用化

Template specialization with a template

本文关键字:专用      更新时间:2023-10-16

我想在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);

不过,它在您的情况下不起作用,因为您不能重载只更改其返回类型的函数。