使用模板的模板专用化
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);
不过,它在您的情况下不起作用,因为您不能重载只更改其返回类型的函数。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 调用专用模板时出错"no matching function for call to [...]"
- 模板专用化(按容器):value_type
- 静态数据成员模板专用化的实例化点在哪里
- 特征 3 类的模板专用化
- Visual Studio 2017 不允许我创建 C++ 专用模板
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 具有常量引用参数的函数模板专用化
- 使用其他模板的模板专用化
- 使用专用显卡进行 OpenGL 渲染时帧速率较低
- 嵌套模板显式专用化
- 如何检查模板专用化是否是基本模板的子类?
- C++:部分模板专用化用例
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 使用对象的基类部分模板专用化对对象进行哈希处理::哈希
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 为什么依赖模板类型在部分专用化中不可推导?
- 如何为静态常量模板化专用整数值分配存储
- 模板类的部分模板专用化,如 std::function
- 合并一组模板专用化