Equ*_*ver 4 c++ lambda return-type unique-ptr c++11
我的应用程序编译器最多只能支持c++11。
下面是我的项目的代码,函数get_conn()返回std::unique_ptr自定义删除器(deleter需要两个参数)。我正在使用auto关键字作为返回类型,但是它给出了一个错误,例如if是否用c++11(用编译很好c++14)
error: ‘get_conn’ function uses ‘auto’ type specifier without trailing return type
Run Code Online (Sandbox Code Playgroud)
示范代码示例:
#include <iostream>
#include <functional>
#include <memory>
using namespace std;
// Dummy definition of API calls
int* open_conn (int handle)
{
return new int;
}
void close_conn (int handle, int *conn)
{}
auto get_conn (int handle)
{
// API call
int* conn = open_conn (handle);
auto delete_conn = [](int *conn, int handle) {
// API call
close_conn (handle, conn);
delete conn;
};
auto delete_binded = std::bind (delete_conn, std::placeholders::_1, handle);
return std::unique_ptr<int, decltype(delete_binded)> (conn, delete_binded);
}
int main()
{
int handle = 2; // suppose
auto c = get_conn (handle);
if (!c)
cout << "Unable to open connection\n";
return 0;
};
Run Code Online (Sandbox Code Playgroud)
如何将auto关键字替换std::unique_ptr为兼容代码的实际返回类型c++11?
我尝试了以下返回类型,但失败了
std::unique_ptr<int, void(*)(int *,int)> get_conn(int handle)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
回到函子!
auto函数的返回类型是c ++ 14功能。为了提供实际的返回类型,您可以提供如下的函子(如注释中提到的@IgorTandetnik)。优点是您不再需要std::bind。
struct DeleteConn // functor which subsituts the lambda and `std::bind`
{
int _handle;
explicit DeleteConn(int handle): _handle{ handle } {}
void operator()(int* conn) const
{
// API call
close_conn(_handle, conn);
delete conn;
}
};
std::unique_ptr<int, DeleteConn> get_conn(int handle)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ---> now you can provide the actual type.
{
// API call
int* conn = open_conn(handle);
DeleteConn delete_conn{ handle };
return std::unique_ptr<int, DeleteConn>(conn, delete_conn);
}
Run Code Online (Sandbox Code Playgroud)
另外,您也可以将lambda函数delete_conn从函数中移出,get_conn并使用尾随返回类型,它是c ++ 11的特色。
namespace inter {
auto delete_conn = [](int* conn, int handle)
{
// API call
close_conn(handle, conn);
delete conn;
};
}
auto get_conn(int handle)
->std::unique_ptr<int, decltype(std::bind(inter::delete_conn, std::placeholders::_1, handle))>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --->Trailing return type
{
// API call
int* conn = open_conn(handle);
auto delete_binded = std::bind(inter::delete_conn, std::placeholders::_1, handle);
return std::unique_ptr<int, decltype(delete_binded)>(conn, delete_binded);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |