从返回类型推断类型T的模板 [英] Templates inferring type T from return type
本文介绍了从返回类型推断类型T的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下模板:
template <class T>
vector<T> read_vector(int day)
{
vector<T> the_vector;
{...}
return the_vector;
}
我希望能够做类似的事情
I would like to be able to do something like
vector<int> ints = read_vector(3);
vector<double> doubles = read_vector(4);
C ++模板是否可以从调用它们的时间推断出返回类型,还是我应该将虚拟参数传递给具有想要矢量具有的类型的模板?后者有效,但更麻烦.
Is it possible for C++ templates to infer the return type from when they're called, or should I just pass a dummy argument to the template with the type I want to the vector to have? The latter works but is messier.
推荐答案
#include <vector>
struct read_vector
{
int day;
explicit read_vector(int day) : day(day) {}
template <typename T, typename A>
operator std::vector<T, A>()
{
std::vector<T, A> v;
//...
return v;
}
};
int main()
{
std::vector<int> ints = read_vector(3);
std::vector<double> doubles = read_vector(4);
}
这篇关于从返回类型推断类型T的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文