I'm playing around with callback functions and wish to register multiple functions via std::bind
that differ in signatures (altough they all return void
). Assigning the result of the std::bind
to the std::variant
yields in a "conversion to non-scalar type" error. Is it an ambiguity error? Can I provide the compiler with more information?
Dropping the std::bind
(which allows the assignment) is not an option as I wish to register the callbacks using some
template <typename Function, typename... Args>
void register(Function &&f, Args &&... args)
{
variant_of_multiple_func_types = std::bind(f, args...);
}
For example:
std::variant<std::function<void()>, int> v = std::bind([]() noexcept {});
works, but
std::variant<std::function<void()>, std::function<void(int)>> v = std::bind([]() noexcept {});
does not, while I expect it to compile into a std::variant
containing a std::function<void()>
.
I get the following compilation error in GCC 7.4.0 with -std=c++17
:
error: conversion from ‘std::_Bind_helper<false, main(int, char**)::<lambda()> >::type {aka std::_Bind<main(int, char**)::<lambda()>()>}’ to non-scalar type ‘std::variant<std::function<void()>, std::function<void(int)> >’ requested
std::variant<std::function<void()>, std::function<void(int)>> v = std::bind([]() noexcept {});
noexcept
be specified for the lambda in the working example for compilation to pass? – Furfurannoexcept
be specified for the lambda in the working example"?. Omitting thenoexcept
still works for me using the same compiler and flags. – Currantstd::bind
with lambda?std::bind
was useful when lambda could not be used. In your codestd::bind
is just obsolete. – Floweredstd::bind([]() noexcept {})("lot", "of", "unused", "parameter")
is valid. you can pass any number of parameter to the bind object, it is mostly needed for theplace_holder
(std::bind([](int) {/*..*/}, place_holder::_5)
). – Jodhpurs-Werror=noexcept
is specified. – Furfuranstd::bind
with lambdas for brevity. In actual code I would only use it here inside the templatedregister
function. – Furfuran