繁体   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