是矢量<auto>不允许 ?(错误:'auto' 的无效使用) [英] Is vector<auto> not allowed ? (error: invalid use of ‘auto’)

查看:24
本文介绍了是矢量<auto>不允许 ?(错误:'auto' 的无效使用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

#include <cstdlib>
#include <vector>

using namespace std;

int main()
{
   auto a = -SOME_CONST_MAX;
   vector<auto> myVec {a, a, a, a};
}

我不知道 SOME_CONST_MAX 的类型,但我想制作 -SOME_CONST_MAX 类型的向量.我假设 vector 会起作用,因为它会从 a 的类型推断出来.

I don't know the type of the SOME_CONST_MAX but I want to make a vector of the type of -SOME_CONST_MAX. I assumed vector<auto> would work as it will deduce from type of a.

我正在运行这些错误:g++ -std=c++14 main.cpp

main.cpp:9:9: error: invalid use of ‘auto’
  vector<auto> myVec {a, a, a, a};
         ^
main.cpp:9:13: error: template argument 1 is invalid
  vector<auto> myVec {a, a, a, a};
             ^
main.cpp:9:13: error: template argument 2 is invalid
main.cpp:9:32: error: scalar object ‘myVec’ requires one element in initializer
  vector<auto> myVec {a, a, a, a};
                                ^

是否不允许使用 vector?我做错了什么?

Is vector<auto> not allowed? What am I doing wrong?

推荐答案

我觉得 Slava 的解决方案非常简单优雅

I find Slava's solution really simple and elegant

vector<decltype(a)> myVec {a, a, a, a};

但只是为了展示另一种方式,您可以使用variadic模板函数

But just to show another way, you can use the variadic template function

template <typename T, typename ... Ts>
std::vector<T> getVect (T const & t, Ts const & ... ts)
 { return { t, ts... } ; }

您可以再次使用auto

auto myVec = getVect(a, a, a, a, a);

这篇关于是矢量&lt;auto&gt;不允许 ?(错误:'auto' 的无效使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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