Reputation: 319
I am trying out c++ lambda functions:
This works:
std::function<std::string(std::string)>lambda = [] (std::string message) -> std::string
{
return std::string("test");
};
i can call the function with std::cout << lambda(std::string("in"));
, and it prints "test"
.
however if i pass another type (std::istream
) it wont compile. A mapping from std::istream
to any type, for example string should be the final goal. I'm going to use templates for this purpose. :
std::function<std::string(std::istream)>lambda = [] (std::istream message) -> std::string
{
return std::string("test");
};
This is the output from g++:
g++ -I"/home/***/workspace.cpp/unrealcv-renderer/include" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/unrealcv_renderer.d" -MT"src/unrealcv_renderer.o" -o "src/unrealcv_renderer.o" "../src/unrealcv_renderer.cpp"
../src/unrealcv_renderer.cpp: In constructor ‘event_camera_simulator::UnrealCVRenderer::UnrealCVRenderer(std::__cxx11::string, std::__cxx11::string)’:
../src/unrealcv_renderer.cpp:23:8: error: conversion from ‘event_camera_simulator::UnrealCVRenderer::UnrealCVRenderer(std::__cxx11::string, std::__cxx11::string)::<lambda(std::istream)>’ to non-scalar type ‘std::function<std::__cxx11::basic_string<char>(std::basic_istream<char>)>’ requested
};
^
What is causing trouble here?
Upvotes: 1
Views: 92
Reputation: 170163
The problem is that you pass the std::istream
by value, which possibly necessitates a copy, and that is a non-copy-able class.
A possible solution would be to accept by reference instead:
std::function<std::string(std::istream&)>lambda = [] (std::istream& message) -> std::string
{
return std::string("test");
};
Upvotes: 9