【发布时间】:2017-12-26 07:07:06
【问题描述】:
我有一个模板函数,我想在其中生成一个未知类型的向量。我试图让它自动,但编译器说它是不允许的。
模板函数获取迭代器或指针,如在随后的主函数内的测试程序中所见。如何解决问题?
template<class Iter>
auto my_func(Iter beg, Iter end)
{
if (beg == end)
throw domain_error("empty vector");
auto size = distance(beg, end);
vector<auto> temp(size); // <--HERE COMPILER SAYS CANNOT BE AUTO TYPE
copy(beg, end, temp->begin);
.
.
return ....
}
int main()
{
int bips[] = {3, 7, 0, 60, 17}; // Passing pointers of array
auto g = my_func(bips, bips + sizeof(bips) / sizeof(*bips));
vector<int> v = {10, 5, 4, 14}; // Passing iterators of a vector
auto h = my_func(v.begin(), v.end());
return 0;
}
【问题讨论】:
-
您希望它只与一对迭代器一起工作,还是您可以接受调用者提供所需类型的解决方案?
-
即使允许,
vector<auto> temp(size);也不包含任何关于编译器auto应该是什么的线索 -
std::vector<decltype(*beg)>,也许。此外,您不需要distance或copy:只需std::vector<decltype(*beg)> temp(beg, end); -
当你进入 C++17 时,
auto可能已经工作了,你可以直接写std::vector temp(beg, end);并通过模板推导计算出auto一定意味着iterator_traits<Iter>::value_type。 -
你知道吗:你可以写
std::end(bips)而不是std::end(bips)
标签: c++ templates stl iterator