我想在C++ 11中定义以下函数:
// This is the general function that should
// never been instantiated
//
template <typename T>
T load(const std::string& filename) {
return T{};
}
Run Code Online (Sandbox Code Playgroud)
适用于各种类型.
我想将这个函数专门用于类型为std :: vector <S>(或任何模板化类)的类.就像是 :
template <typename std::vector<S>>
std::vector<S> load(const std::string& filename) {
// Implementation
}
Run Code Online (Sandbox Code Playgroud)
这段代码显然不起作用.但我怎么能这样做?
谢谢你的帮助.
函数不能是部分专用的,但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);
}
Run Code Online (Sandbox Code Playgroud)