decltype vs auto

后端 未结 4 1812
自闭症患者
自闭症患者 2021-01-30 04:17

As I understand it, both decltype and auto will attempt to figure out what the type of something is.

If we define:

int foo () {         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 04:23

    modify @Mankarse's example code,I think a better one blew:

    #include 
    int global = 0;
    int& foo()
    {
       return global;
    }
    
    int main()
    {
        decltype(foo()) a = foo(); //a is an `int&`
        auto b = foo(); //b is an `int`
        b = 2;
    
        std::cout << "a: " << a << '\n'; //prints "a: 0"
        std::cout << "b: " << b << '\n'; //prints "b: 2"
        std::cout << "global: " << global << '\n'; //prints "global: 0"
    
        std::cout << "---\n";
    
        //a is an `int&`
        a = 10;
    
        std::cout << "a: " << a << '\n'; //prints "a: 10"
        std::cout << "b: " << b << '\n'; //prints "b: 2"
        std::cout << "global: " << global << '\n'; //prints "global: 10"
    
        return 0;
    
    }
    

提交回复
热议问题