C++ 从返回类型推断类型T的模板
我有一个模板如下:C++ 从返回类型推断类型T的模板,c++,templates,generic-programming,C++,Templates,Generic Programming,我有一个模板如下: template <class T> vector<T> read_vector(int day) { vector<T> the_vector; {...} return the_vector; } 模板 向量读取向量(整数天) { 向量_向量; {...} 返回_向量; } 我希望能够做一些像 vector<int> ints = read_vector(3); vector<double> do
template <class T>
vector<T> read_vector(int day)
{
vector<T> the_vector;
{...}
return the_vector;
}
模板
向量读取向量(整数天)
{
向量_向量;
{...}
返回_向量;
}
我希望能够做一些像
vector<int> ints = read_vector(3);
vector<double> doubles = read_vector(4);
vector ints=读取向量(3);
向量加倍=读取向量(4);
< C++ >是否可以从调用它们时推断返回类型,或者我应该只将一个哑参数传递给模板,并使其具有向量所要的类型吗?后者起作用,但更为混乱。#include
#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);
}
结构读取向量
{
国际日;
显式读取向量(整数天):天(天){
模板
运算符std::vector()
{
std::向量v;
//...
返回v;
}
};
int main()
{
std::vector ints=读取向量(3);
std::vector doubles=读取向量(4);
}
否,在这种情况下,您需要指定类型
read\u vector
。编译器无法推断返回类型。非常聪明,+1。您是否介意为那些可能不知道其工作原理的人解释一下?这是否需要分配器参数a
?GillBates部分是,否则它将默认为std::allocator
,并在目标类型使用不同的分配器时导致扣减失败此具有(易于修复)缺陷。标准并不能真正保证std::vector
是由两个参数组成的模板。@SergeyA即使如此,如果普通人无法使用这些参数,为什么转换运算符还要推断出任何其他参数?