特定模板类型的功能专用化
Specialization of function for a specific template type
请考虑以下事项:
template <typename TResult> inline TResult _from_string(const string& str);
template <> inline unsigned long long _from_string<unsigned long long>(const string& str) {
return stoull(str);
}
我可以这样调用该函数:
auto x = _from_string<unsigned long long>("12345");
现在我想为vector
s写另一个专业,即:
template <typename T> inline vector<T> _from_string<vector<T>>(const string& str) {
// stuff that should be done only if the template parameter if a vector of something
}
这样我就可以做这样的事情:
auto x = _from_string<vector<int>>("{1,2,3,4,5}");
但是,当我编译函数(在 MSVC 2015 下)时,我收到错误 C2768:"非法使用显式模板参数",这是有道理的,因为我不应该在专用化中使用新的模板参数。
如何重写vector
专业化以使其正常工作?
函数模板只能是完全专用的,不能是部分专用的;但类模板可以。
// primary class template
template <typename T>
struct X {
static T _from_string(const string& str);
};
// full specialization for unsigned long long
template <>
struct X<unsigned long long> {
static unsigned long long _from_string(const string& str) {
return stoull(str);
}
};
// partial specialization for vector<T>
template <typename T>
struct X<vector<T>> {
static vector<T> _from_string(const string& str) {
// stuff that should be done only if the template parameter if a vector of something
}
};
// helper function template
template <typename TResult>
inline TResult _from_string(const string& str) {
return X<TResult>::_from_string(str);
}
然后
auto x1 = _from_string<unsigned long long>("12345");
auto x2 = _from_string<vector<int>>("{1,2,3,4,5}");
住
您不能部分专用化功能。
您很少应该完全专注于功能。
处理此问题的更好方法是使用重载。 返回类型上的重载只需要一个额外的参数:
template<class T> struct tag_t{constexpr tag_t(){}; using type=T;};
template<class T>constexpr tag_t<T> tag{};
template <typename TResult> inline TResult _from_string(const string& str){
return _from_string( tag<TResult>, str );
}
现在我们从来没有专门_from_string
,我们只是重载了 2 arg 版本。
inline unsigned long long _from_string(tag_t<unsigned long long>, const string& str) {
return stoull(str);
}
以上甚至不是模板。
template <class T, class A>
std::vector<T,A> _from_string(tag_t<std::vector<T,A>>, const string& str) {
// stuff that should be done only if the target type is a vector of something
}
以上是一个模板,但不是模板的专业化。
作为奖励,如果您有自定义类型 bob
在 namespace foo
,您只需用 namespace foo
编写_from_string( tag_t<bob>, std::string const& )
,在大多数情况下,称为"ADL"的东西会自动找到它。
使用标记进行基于重载的调度清晰而简单,允许您自定义相关命名空间中的内容。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- .cpp和.h文件中的模板专用化声明
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 调用专用模板时出错"no matching function for call to [...]"
- 模板专用化(按容器):value_type
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- OpenMP 慢速专用功能
- C 专用模板功能接收文字字符串
- 在库中展示ConstexPR专用模板功能
- 将过载功能转换为专用功能模板
- 特定模板类型的功能专用化
- 模板专用化和普通旧功能
- 通过C 传递专用功能指针
- C++模板功能专用化
- C++具有继承功能的模板部分专用化
- C++中的专用朋友功能
- 可以是类模板内专用于类模板外的模板功能