vector< auto>是不允许 ? (错误:无效使用“自动") [英] Is vector<auto> not allowed ? (error: invalid use of ‘auto’)

查看:256
本文介绍了vector< 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<auto>会起作用,因为它将根据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

I'm getting these errors running: 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<auto>吗?我在做什么错了?

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

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

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