小编law*_*log的帖子

模板化功能模板专业化

我想为模板函数编写一个特殊化,其中针对它的特殊化类型本身就是一个模板化类型。(我使用的是C ++ 11或更高版本。)

在下面的示例代码中,我具有的泛型函数convertTo和一个专门的工作特性int,允许我使用convertTo<int>(s)(如图所示)。但是我无法弄清楚如何为例如编写专业化知识std::set<T>。这是我尝试的:

#include <string>
#include <sstream>
#include <set>
#include <unordered_set>
using namespace std;

// generic version
template<class T> T convertTo(const char* str) {
  T output;
  stringstream ss(str, stringstream::in);
  ss >> output;
  return output;
}

// specialization for int. works.
template <>
int convertTo<int>(const char* str) {
  return atoi(str);
}

template <>
template<class T> set<T> convertTo<set<T>>(const char* str) {
  set<T> S;
  // TODO split str by comma, convertTo<T>(each element) and put …
Run Code Online (Sandbox Code Playgroud)

c++ templates specialization c++11

6
推荐指数
1
解决办法
552
查看次数

标签 统计

c++ ×1

c++11 ×1

specialization ×1

templates ×1