在C ++中初始化模板函数内的auto(未知)类型的向量 [英] Initializing a vector of auto (unknown) type inside a template function in C++

查看:113
本文介绍了在C ++中初始化模板函数内的auto(未知)类型的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板函数,我想在其中生成一个未知类型的向量。我尝试将其设置为auto,但编译器表示不允许这样做。

I have a template function inside which I want to generate a vector which is of an unknown type. I tried to make it auto, but compiler says it is not allowed.

模板函数获取迭代器或指针,如后面的main函数中的测试程序中所示。如何解决问题?

The template function gets either iterators or pointers as seen in the test program inside the followed main function. How can the problem be fixed?

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;
}


推荐答案

你不能使用 std :: vector auto 。您可以改用 std :: iterator_traits

You cannot use a std::vector of auto. You might use std::iterator_traits instead:

std::vector<typename std::iterator_traits<Iter>::value_type> temp(size);

这篇关于在C ++中初始化模板函数内的auto(未知)类型的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆