我有一个传统的C lib,而function(setsockopts)想要一个指针参数.在C++ 11(gcc 4.8)中,我可以在不初始化命名变量的情况下传递此参数吗?
我有以下不满意的解决方案:
#include <iostream>
#include <memory>
int deref(int const * p) {return * p;}
using namespace std;
int main() {
int arg = 0; cout << deref(& arg) << endl;
// works, but is ugly (unnecessary identifier)
cout << deref(& 42) << endl;
// error: lvalue required as unary ‘&’ operand
cout << deref(& * unique_ptr<int>(new int(42))) << endl;
// works, but looks ugly and allocates on heap
}
Run Code Online (Sandbox Code Playgroud)
ken*_*ytm 24
我只是创建一个包装器,setsockopt如果这确实是一个麻烦(未经测试)
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);
Run Code Online (Sandbox Code Playgroud)
Man*_*rse 20
编写一个函数模板来将rvalues转换为lvalues:
template<typename T>
T &as_lvalue(T &&val) {
return val;
}
Run Code Online (Sandbox Code Playgroud)
现在,使用它:
deref(&as_lvalue(42));
Run Code Online (Sandbox Code Playgroud)
警告:这不会延长临时的生命周期,因此在创建临时表达式的完整表达式结束后,不得使用返回的引用.
eca*_*mur 10
您可以绑定const对临时的引用:
cout << deref(addressof<const int>(42)) << endl;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1538 次 |
| 最近记录: |