In C++11, how can I get a temporary lvalue without a name?

后端 未结 3 1336
慢半拍i
慢半拍i 2021-01-01 16:12

I have a traditional C lib and a function (setsockopts) wants an argument by pointer. In C++11 (gcc 4.8), can I pass this argument without initializing a named

3条回答
  •  臣服心动
    2021-01-01 16:41

    Write a function template to convert rvalues to lvalues:

    template
    T &as_lvalue(T &&val) {
        return val;
    }
    

    Now, use it:

    deref(&as_lvalue(42));
    

    Warning: this doesn't extend the lifetime of the temporary, so you mustn't use the returned reference after the end of the full-expression in which the temporary was created.

提交回复
热议问题