我正在使用一个大量使用回调 lambda 函数的 C++ Web 框架。auto正如您可能猜到的那样,由于必须声明非常长的声明,因此通常将 lambda 的参数指定为。
现在我使用decltype()运算符来查找推导的正确类型,auto以便我可以声明相同类型的向量。当向量声明发生在 lambda 中时,一切都很好。
我的问题开始于这个向量需要使用 lambdasauto参数的类型信息在外部范围内声明。下面是一个简单的例子:
std::vector<T> vec; // I want the type information to be inferred just like vec2 from lambda below
auto func = [](auto parameter){
std::vector<decltype(parameter)> vec2; // No problem here.
};
这可能吗?
更新:
我使用的框架是uWebSockets. 这是示例代码:
using DataType = std::string;
// I had to go get type information from the source code.
static std::vector<uWS::WebSocket<false, true, DataType> *> users;
uWS::App app {};
app.ws<DataType>("/*", {
.open = [](auto * ws){
// This is also doable
// But not accessible in other lambdas.
static std::vector<decltype(ws)> users2;
// users2.push_back(ws);
users.push_back(ws);
ws->subscribe("sensors/+/house");
},
.close = [](auto *ws, int code, std::string_view message){
users.erase(std::remove(users.begin(), users.end(), ws), users.end());
// Not possible because not accessible.
//users2.erase(std::remove(users2.begin(), users2.end(), ws), users2.end());
std::cout << "Client disconnected!" << std::endl;
},
.message = [](auto *ws, std::string_view message, uWS::OpCode opCode){
try{
std::string message2 = std::string(message) + std::string(" ACK");
for(const auto & ws2 : users)
if(ws != ws2)
ws2->send(message2, opCode);
}catch(std::exception& e){
std::cout << e.what() << std::endl;
}
},
});
现在,在 的任何地方main.cpp,都需要将参数传递给 lambda 函数。这就是主要问题的来源。