How to declare array with auto

前端 未结 4 695
佛祖请我去吃肉
佛祖请我去吃肉 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:44

    decltype works with g++ 4.9.0 20130601 for this:

    #include 
    #include 
    
    static std::ostream& logger = std::clog;
    
    class A {
        static int _counter;
        int _id;
      public:
        A() : _id(++_counter) {
            logger << "\tA #" << _id << " c'tored\n";
        } 
    
        ~A() {
            //logger << "\tA #" << _id << " d'tor\n";
        } 
    
        inline int id() const{
            return _id;
        }
    };
    int A::_counter(0); 
    
    std::ostream& operator<<(std::ostream& os, const A& a) {
        return os << a.id();
    }
    
    int main() {
    
        auto dump = [](const A& a){ logger << a << " ";};
    
        logger << "x init\n";
        A x[5]; 
        logger << "x contains: "; std::for_each(x, x+5, dump);
    
        logger << "\ndecltype(x) y init\n";
        decltype(x) y;
        logger << "y contains: ";  std::for_each(y, y+5, dump);
        logger << std::endl;
    
        return 0;
    }
    

    Output:

    x init
        A #1 c'tored
        A #2 c'tored
        A #3 c'tored
        A #4 c'tored
        A #5 c'tored
    x contains: 1 2 3 4 5 
    decltype(x) y init
        A #6 c'tored
        A #7 c'tored
        A #8 c'tored
        A #9 c'tored
        A #10 c'tored
    y contains: 6 7 8 9 10 
    

提交回复
热议问题