模板专业化与模板

时间:2015-11-12 13:29:38

标签: c++ templates

我想在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&lt;类型的族。 S&gt; (或任何模板类)。类似的东西:

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

此代码显然不起作用。但我怎么能这样做?

感谢您的帮助。

2 个答案:

答案 0 :(得分:6)

函数不能是部分专用的,但是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);
}

答案 1 :(得分:2)

在C ++中,没有功能模板部分特化。您想要做的是为您的函数模板定义重载,例如:

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

尽管如此,它在你的情况下是行不通的,因为你不能重载只改变其返回类型的函数。