I have a legacy template function I'm trying to call that has a slew of specializations for function pointers with different numbers of arguments. I'm writing a new template function of my own that take some arbitrary kind of non-capturing lambda and needs to pass it to the other library. If I do this directly, then the template resolution fails. If however I explicitly cast it to be related function pointer type, things work.
The problem then is how to make my template code get that function pointer type from the lambda's type or force the explicit conversion without explicitly referencing the type.
Just use unary-plus to convert a lambda to a function pointer, as in:
auto* f = +[]{ std::cout << "Hello, world!\n"; }; // f is of type void (*)()
Related
In boost.asio example of asynchronous UDP server we can find next code:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
..........
void handle_receive(const boost::system::error_code& error,
std::size_t /*bytes_transferred*/)
According to specification of basic_datagram_socket::async_receive_from function, its prototype is
template<
typename MutableBufferSequence,
typename ReadToken = DEFAULT>
DEDUCED async_receive_from(
const MutableBufferSequence & buffers,
endpoint_type & sender_endpoint,
ReadToken && token = DEFAULT);
when token may be a function with prototype
void handler(
const boost::system::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes received.
);
I do not understand two things (at least)
How bind work here? It accept handle_receive pointer, udp_server object (what for?) and two placeholders. How does it turn to function that is called at the end of asynchronous call and get context varibles?
How does handle_receive function access a recv_buffer_ which is an argument of async_receive_from function but not of handle_receive?
Bind returns a bound function object. There's extensive documentation about how it works and why you'd use it:
https://www.boost.org/doc/libs/1_77_0/libs/bind/doc/html/bind.html
also see https://en.cppreference.com/w/cpp/utility/functional/bind
udp_server object (what for?)
(Non-static) member functions take an implicit this pointer argument to the class instance (object). So a 2-argument non-static member function void X::foo(int,int) consttakes 3 arguments:X const*, int, int`.
How does handle_receive function access a recv_buffer_ which is an argument of async_receive_from function but not of handle_receive?
recv_buffer_ is a data member of the same class (udp_server), so in handle_receive it is implicitly accessing it as this->recv_buffer_. This is very elementary C++, so I recommend maybe reading a good introduction or book if this is new for you.
I am trying to write a wrapper on top of winapi. I want to wrap functions that accept pointers for callback functions.
As an example, consider this:
// The unsafe callback type the FFI function accepts
type UnsafeCallback = unsafe extern "system" fn(exception_info: *mut ExceptionInfo) -> u32;
// The safe callback type my function should accept
type SafeCallback = fn(exception_info: &ConvertedExceptionInfo) -> u32;
The functions that will be used:
// The function exposed by winapi
unsafe extern "system" fn SetExceptionHandler(handler: UnsafeCallback);
// The function I want to expose in my library
fn SetExceptionHandler(handler: SafeCallback);
I want to create a wrapping function that looks like this:
unsafe extern "system" fn(exception_info: *mut ExceptionInfo) -> u32 {
let result = panic::catch_unwind(|| {
// Convert ExceptionInfo into ConvertedExceptionInfo. I know this is undefined behavior, but its only here
// to demonstrate program flow
let converted_exception_info: ConvertedExceptionInfo = (*exception_info).into();
// Call the corresponding safe function (as to how we get the function pointer here, that's
// the whole question)
return safe_callback(&converted_exception_info);
});
return match result {
Ok(val) => val,
Err(_) => _
};
}
I can think of two possibilities to create this wrapping function:
Creating a wrapping function at runtime
Create a closure or similar construct inside the safe
SetExceptionHandler method.
I have no idea how to get the closure across the FFI boundary.
Exposing a conversion macro and generating the function at compile time
Edit the SetExceptionHandler function to accept the UnsafeCallback
type.
Then I could create a macro that generates the wrapping function at compile time and expose this macro to the user.
I would have to expose unsafe extern parameters again, so it is not
how I would prefer to do it.
I have no idea how to structure such a macro or if this is even possible.
Is my first idea possible and feasible? If so, how could this be done?
If not, is writing a macro like the second idea possible and feasible? If so, how could this be done?
Based on
How do I create a Rust callback function to pass to a FFI function?
How do I convert a Rust closure to a C-style callback?
How do I pass a closure through raw pointers as an argument to a C function?
I get the impression that my first idea is probably not possible with the exception of something called trampolining.
Is trampolining possible in safe Rust and in this situation?
After much searching, i have found a blog post that explains a nice solution for the problem of wrapping callbacks. Article here
"Theory" question if you will.
In order to execute/make use of the move constructor in a class, do I always have to use std::move(...) to tell the compiler that I wish to 'move' an object rather than copy it?
Are there any cases where the compiler will invoke the move constructor for me without the use of std::move? (My guess would be in function return values?)
According to cppreference.com (http://en.cppreference.com/w/cpp/language/move_constructor):
The move constructor is called whenever an object is initialized from xvalue of the same type, which includes
initialization, T a = std::move(b); or T a(std::move(b));, where b is of type T;
function argument passing: f(std::move(a));, where a is of type T and f is void f(T t);
function return: return a; inside a function such as T f(), where a is of type T which has a move constructor.
In most cases, yes std::move is needed.
The compiler will invoke the move constructor without std::move when:
returning a local variable by value
when constructing an object from an rvalue of the same type
In all other cases, use std::move. E.g.:
struct S {
std::string name;
S(std::string name) : name(std::move(name)) {}
};
and
std::unique_ptr<Base> func() {
auto p = std::make_unique<Derived>();
return std::move(p); // doesn't work without std::move
}
std::move is just a cast.
unique_ptr<int> global;
auto v = unique_ptr<int>(global); // global is a lvalue, therefore the
unique_ptr(unique_ptr<T>&v) constructor that accepts lvalue references is called.
auto v = unique_ptr<int>(std::move(global)); // move returns a &&rvalue reference, therefore the
unique_ptr(unique_ptr<T>&&v) constructor that accepts &&rvalue references is used.
When the criteria for elision of a copy operation are met and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
therefore,
unique_ptr<int> hello()
{
unique_ptr<int> local;
return local;
// local is an lvalue, but since the critera for elision is met,
// the returned object is created using local as if it was an rvalue
}
Also,
unique_ptr<int> hello = std::unique_ptr<int>();
// we have a pure rvalue in the right, therefore no std::move() cast is needed.
I am trying to get more familiar with the C++11 standard by implementing the std::iterator on my own doubly linked list collection and also trying to make my own sort function to sort it.
I would like the sort function to accept a lamba as a way of sorting by making the sort accept a std::function, but it does not compile (I do not know how to implement the move_iterator, hence returning a copy of the collection instead of modifying the passed one).
template <typename _Ty, typename _By>
LinkedList<_Ty> sort(const LinkedList<_Ty>& source, std::function<bool(_By, _By)> pred)
{
LinkedList<_Ty> tmp;
while (tmp.size() != source.size())
{
_Ty suitable;
for (auto& i : source) {
if (pred(suitable, i) == true) {
suitable = i;
}
}
tmp.push_back(suitable);
}
return tmp;
}
Is my definition of the function wrong? If I try to call the function, I recieve a compilation error.
LinkedList<std::string> strings{
"one",
"two",
"long string",
"the longest of them all"
};
auto sortedByLength = sort(strings, [](const std::string& a, const std::string& b){
return a.length() < b.length();
});
Error: no instance of function template "sort" matches the argument
list argument types are: (LinkedList, lambda []bool
(const std::string &a, const std::string &)->bool)
Additional info, the compilation also gives the following error:
Error 1 error C2784: 'LinkedList<_Ty> sort(const
LinkedList<_Ty> &,std::function)' : could not
deduce template argument for 'std::function<bool(_By,_By)>'
Update: I know the sorting algorithm is incorrect and would not do what is wanted, I have no intention in leaving it as is and do not have a problem fixing that, once the declaration is correct.
The problem is that _By used inside std::function like this cannot be deduced from a lambda closure. You'd need to pass in an actual std::function object, and not a lambda. Remember that the type of a lambda expression is an unnamed class type (called the closure type), and not std::function.
What you're doing is a bit like this:
template <class T>
void foo(std::unique_ptr<T> p);
foo(nullptr);
Here, too, there's no way to deduce T from the argument.
How the standard library normally solves this: it does not restrict itself to std::function in any way, and simply makes the type of the predicate its template parameter:
template <typename _Ty, typename _Pred>
LinkedList<_Ty> sort(const LinkedList<_Ty>& source, _Pred pred)
This way, the closure type will be deduced and all is well.
Notice that you don't need std::function at all—that's pretty much only needed if you need to store a functor, or pass it through a runtime interface (not a compiletime one like templates).
Side note: your code is using identifiers which are reserved for the compiler and standard library (identifiers starting with an underscore followed by an uppercase letter). This is not legal in C++, you should avoid such reserved identifiers in your code.
I am currently writing a program in C++0x which I am fairly new to.
I am setting up callbacks between objects and using lambda to match the types (like boost::bind() does in ways)
If I call a function in the asio library like:
socket_.async_read_some(buffer(&(pBuf->front()), szBuffer),
[=](const boost::system::error_code &error, size_t byTrans) {
this->doneRead(callBack, pBuf, error, byTrans); });
This compiles fine, and runs as expected, 'doneRead' is called back from 'async_read_some'
so I have a similar call back in my own code:
client->asyncRead([=](string msg){this->newMsg(msg); });
This takes just a string, and asyncReads prototype is as follows
void ClientConnection::asyncRead(void(*callBack)(string))
But I get this compile error:
Server.cpp: In member function ‘void
Server::clientAccepted(std::shared_ptr,
const boost::system::error_code&)’:
Server.cpp:31:3: error: no matching
function for call to
‘ClientConnection::asyncRead(Server::clientAccepted(std::shared_ptr,
const
boost::system::error_code&)::)’
Server.cpp:31:3: note: candidate is:
ClientConnection.h:16:9: note: void
ClientConnection::asyncRead(void
(*)(std::string))
ClientConnection.h:16:9: note: no
known conversion for argument 1 from
‘Server::clientAccepted(std::shared_ptr,
const
boost::system::error_code&)::’
to ‘void (*)(std::string)’
How can this issue be resolved?
Your lambda captures this implicitly. A lambda that captures things cannot convert to a raw function pointer.
So you need to write asyncRead so it accepts the lambda function object directly, instead of letting it convert to a function pointer
template<typename CallbackType>
void ClientConnection::asyncRead(CallbackType callback);
Alternatively, if you don't want to write this as a template, you can use a polymorphic function object wrapper
void ClientConnection::asyncRead(std::function<void(string)> callBack);
I would also consider changing the callback's interface so it accepts the string by const reference (unless all the callback implementations inherently want to modify or save/move the passed string internally, which seem unlikely in your case).