How to declare array with auto

前端 未结 4 697
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 01:03

I have been playing with auto and I noticed that for most cases you can replace a variable definition with auto and then assign the type.

I

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 01:45

    Not exactly the same thing, and it's a bit ugly, but it is possible to deduce the element type from a list initializer and declare the array directly, as follows:

    template
    struct array_trait
    {
        using element_type = T;
        array_trait(T(&&)[]);
    };
    
    decltype(array_trait({4,5,7}))::element_type a[] = {4,5,7};
    
    std::cout << typeid(a).name() << std::endl;
    
    for (unsigned i = 0; i < 3; i++)
        std::cout << a[i] << std::endl;
    

    The type should be int[3] and the output should be 4 5 7.

提交回复
热议问题