c – 模板参数的模糊模板重载是一个容器
发布时间:2020-12-16 10:20:24 所属栏目:百科 来源:网络整理
导读:请考虑以下示例: #include string#include vectorusing std::string;using std::vector;template typename Tconst T GetValue(){ return T(); // some value}template typename Tconst vectorT GetValue(){ return vectorT(); // some vector of values}int
|
请考虑以下示例:
#include <string>
#include <vector>
using std::string;
using std::vector;
template <typename T>
const T GetValue()
{
return T(); // some value
}
template <typename T>
const vector<T> GetValue()
{
return vector<T>(); // some vector of values
}
int main(int argc,char* argv[])
{
int i = GetValue<int>();
vector<int> = GetValue<vector<int>>();
return 0;
}
我有两个模板函数,它们应该根据给定的类型解析某些存储中的值.第一个应该完成简单数据类型的工作,第二个应该只用于简单数据类型的向量. 任何帮助将不胜感激! 解决方法
一种简单的方法是使用out-param,以便可以从参数中推导出模板参数:
#include <vector>
using std::vector;
template <typename T>
void GetValue(T &t)
{
t = T(); // some value
}
template <typename T>
void GetValue(vector<T> &v)
{
v = vector<T>(); // some vector of values
}
int main(int argc,char* argv[])
{
int i;
GetValue(i);
vector<int> v;
GetValue(v);
return 0;
}
GetValue(v)不含糊,因为模板参数推导规则说第二次重载是更好的匹配. 这不一定是您想要的界面/样式,但在这种情况下,您可以使用部分特化而不是重载.但这需要一个类,因为函数模板不能部分专门化: #include <vector>
using std::vector;
template <typename T>
struct Getter {
T get(void) {
return T(); // some value
}
};
template <typename T>
struct Getter<vector<T> > {
vector<T> get(void) {
return vector<T>(); // some vector of values
}
};
template <typename T>
T GetValue(void)
{
return Getter<T>().get();
}
int main(int argc,char* argv[])
{
int i = GetValue<int>();
vector<int> v = GetValue<vector<int> >();
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
