Is vector not allowed ? (error: invalid use of ‘auto’)

后端 未结 2 840
情书的邮戳
情书的邮戳 2020-12-20 16:24

I have:

#include 
#include 

using namespace std;

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


        
相关标签:
2条回答
  • 2020-12-20 16:39

    I find Slava's solution really simple and elegant

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

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

    You can use auto again

    auto myVec = getVect(a, a, a, a, a);
    
    0 讨论(0)
  • 2020-12-20 16:49

    If I remember correctly, proposals have been made for vector<auto> syntax. They where not accepted by the C++ standard committee.

    C++17 will introduce something like std::vector bob = {a,a,a,a}; that just works. Note the lack of <auto>. This may just be the language feature, with actual use in std following afterward.

    auto is also added to templates, but auto is always a value never a type. So using auto to replace a type was considered a bad idea.

    Here is a use of 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 a std::integral_constant<int,7>. This is considered useful for many reasons.

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

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

    where we deduce the type of a and pass it to vector.

    0 讨论(0)
提交回复
热议问题