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

后端 未结 3 1246
慢半拍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:40

    You can bind a const reference to a temporary:

    cout << deref(addressof<const int>(42)) << endl;
    
    0 讨论(0)
  • 2021-01-01 16:41

    Write a function template to convert rvalues to lvalues:

    template<typename T>
    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.

    0 讨论(0)
  • 2021-01-01 16:42

    I'd just create a wrapper to setsockopt if that's really a trouble (not tested)

    template <typename T>
    int setsockopt(int socket, int level, int optname, const T& value) {
        return setsockopt(socket, level, optname, &value, sizeof(value));
    }
    
    ...
    
    setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, 1);
    
    0 讨论(0)
提交回复
热议问题