Is there a way to make passing by reference, and passing by value explicit in the function call?

前端 未结 7 1512
北荒
北荒 2021-02-18 13:43

If you were to look at this code,

int x = 0;
function(x);
std::cout << x << \'\\n\';

you would not be able to verify through any me

7条回答
  •  攒了一身酷
    2021-02-18 14:23

    I'm not sure I understand your requirements completely, but maybe this is something you can use:

    template
    void foo( T ) { static_assert( sizeof(T)==0, "foo() requires a std::ref" ); }
    
    void foo( std::reference_wrapper t )
    {
        // modify i here via t.get() or other means of std::reference_wrapper
    }
    
    int main()
    {
        int i = 42;
        // foo( i ); // does not compile, static_assert fires
        foo( std::ref( i ) ); // explicit std::ref visible on the caller's side
    }
    

提交回复
热议问题