#include using namespace std; int main() { au...">

Is the vector <auto> allowed? (error: incorrect use of "auto")

I have:

 #include <cstdlib> #include <vector> using namespace std; int main() { auto a = -SOME_CONST_MAX; vector<auto> myVec {a, a, a, a}; } 

I do not know the type SOME_CONST_MAX , but I want to create a vector of the type -SOME_CONST_MAX . I assumed that vector<auto> would work the way it would infer from type a .

I get these errors: 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}; ^ 

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

+6
source share
2 answers

I find the Slava solution very simple and elegant

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

but just to show a different way using the function of the variation template

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

you can use auto again

 auto myVec = getVect(a, a, a, a, a); 
+10
source

If I remember correctly, the syntax vector<auto> was suggested. They are not accepted by the standard C ++ committee.

C ++ 17 will introduce something like std::vector bob = {a,a,a,a}; that just works. Note the lack of <auto> . It can only be a language function, with actual use in std after that.

auto also added to templates, but auto always a value of never type. Therefore, using auto to replace a type was considered bad.

Here is an example of using auto in a template:

 template<auto x> using constant_t=std::integral_constant<decltype(x),x>; template<auto x> constexpr constant_t<x> constant{}; 

and now constant<7> is std::integral_constant<int,7> . This is considered useful for many reasons.

The answer to your practical problem using current C ++:

 auto a = -SOME_CONST_MAX; std::vector<decltype(a)> myVec {a, a, a, a}; 

where we infer the type a and pass it to vector .

+8
source

Source: https://habr.com/ru/post/1014389/


All Articles