What would be a “Hello, World!” example for “std::ref”?

后端 未结 4 2050
星月不相逢
星月不相逢 2021-01-30 01:54

Can somebody give a simple example which demonstrates the functionality of std::ref? I mean an example in which some other constructs (like tuples, or data type tem

4条回答
  •  遇见更好的自我
    2021-01-30 02:48

    void PrintNumber(int i) {...}
    
    int n = 4;
    std::function print1 = std::bind(&PrintNumber, n);
    std::function print2 = std::bind(&PrintNumber, std::ref(n));
    
    n = 5;
    
    print1(); //prints 4
    print2(); //prints 5
    

    std::ref is mainly used to encapsulate references when using std::bind (but other uses are possible of course).

提交回复
热议问题