Passing to a Reference Argument by Value

前端 未结 7 929
名媛妹妹
名媛妹妹 2021-01-17 14:40

Consider this simple program:

vector foo = {0, 42, 0, 42, 0, 42};
replace(begin(foo), end(foo), foo.front(), 13);

for(const auto& i : foo) co         


        
7条回答
  •  逝去的感伤
    2021-01-17 15:24

    You can write a simple function that takes in a reference and returns a value. this will "convert" the reference into a value. This does generate a temporary but it is unnamed and will be destroyed at the end of the full expression. Something like

    template
    T value(const T& ref)
    {
        return ref;
    }
    

    And then you can use it like

    int main()                                                   
    {                                                            
        vector foo = {0, 42, 0, 42, 0, 42};
        replace(begin(foo), end(foo), value(foo.front()), 13);
    
        for(const auto& i : foo) cout << i << '\t';                                      
    }
    

    output:

    13  42  13  42  13  42
    

    Live Example

提交回复
热议问题