Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用模板进行模板专门化_C++_Templates - Fatal编程技术网

C++ 使用模板进行模板专门化

C++ 使用模板进行模板专门化,c++,templates,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{}; } //这是应该 //从未被实例化过 // 模板 T加载(常量std::字符串和文件名){ 返回T{}; } 适用于各种类型 我想专门为std::

我想在C++11中定义以下函数:

// This is the general function that should
// never been instantiated
//
template <typename T>
T load(const std::string& filename) {
  return T{};
}
//这是应该
//从未被实例化过
//
模板
T加载(常量std::字符串和文件名){
返回T{};
}
适用于各种类型

我想专门为std::vector类型家族(或任何模板类)指定此函数。比如:

template <typename std::vector<S>>
std::vector<S> load(const std::string& filename) {
  // Implementation
}
模板
标准::矢量加载(常量标准::字符串和文件名){
//实施
}
这段代码显然不起作用。但我怎么能做到呢

谢谢您的帮助。

< P> C++中没有函数模板部分特化。您要做的是为函数模板定义重载,如:

// warning: this will not work in your case
template<typename S>
std::vector<S> load(const std::string& filename);
//警告:这在您的情况下不起作用
模板
std::矢量加载(const std::字符串和文件名);

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

函数不能部分专用,但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);
}
模板结构加载\u助手;
模板结构加载辅助程序
{
std::vector运算符()(const std::string和filename)const
{
//您的实现
}
};
模板
T加载(常量std::字符串和文件名){
返回load_helper{}(文件名);
}

您可以检查函数中T的类型,并决定要做什么,有什么问题:模板std::vector load(const std::string&filename){//Implementation}@Human:我已经尝试过了,但它不起作用,这并不奇怪。您所说的不起作用是什么意思?@Human:不编译.OP“can”只按返回类型重载,但每次都必须将函数转换为正确的类型…@Jarod42您确定吗?这不是一个模棱两可的问题吗?你可以这么说。但如果可能的话,我会避免这样做。@Jarod42哇,相当尴尬:)那个演员合法吗?我得承认我不明白为什么它会起作用!如果我想返回一个
向量
load
为什么必须强制转换
load
load
可能是返回
int
std::vector
,因此您必须指定要使用哪个重载。谢谢。这似乎是目前为止最好的方法,