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

前提是你 提交于 2019-11-30 11:12:30

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);

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.

You can bind a const reference to a temporary:

cout << deref(addressof<const int>(42)) << endl;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!