Storing variadic parameter and callback for later usage - c++

I want to create a simple but generic callback with variadic parameters. I also need storing them, because callback will called later in time (from a different thread which uses the storage).
Here's what I have until now:
#include <iostream>
#include <string>
using namespace std;
void fileMgr_DoneWithOtherstuff_DoTheReads() {
FROM SOMESTORAGE get the callback and params
Do the reading
string result = "CONTENT";
Call the callback with result string and params
}
template<class ReadFileCallback, class ...T>
void fileMgr_ReadWithCallback(string filename, ReadFileCallback callback, T ...params) {
cout << "fileMgr_ReadWithCallback is processing file: " << filename << endl;
// string content = "CONTENT";
// callback(content, params...);
SOMESTORAGE = callback + params;
}
void readFileResult(string contents, int id) {
cout << "readFileResult callback: contents=" << contents << ", id=" << id << endl;
}
void readFile(string filename, int id) {
fileMgr_ReadWithCallback(filename, readFileResult, id);
}
int main()
{
int fileId = 1;
readFile("myfile", fileId);
return 0;
}
But I don't want to call callback in fileMgr_ReadWithCallback, because it should be an async method, so I'd rather store the callback function and its parameters, and use it later once File Manager is able to perform the operation.
So the question is, what's the way to store ReadFileCallback and ...T into a struct maybe?
Or if there is better way doing this, let me know please.
I need the variadic arguments, as sometimes the extra param is just an int, but sometimes it can be 2 ints, or 1 string, etc, and I want to keep the FileManager generic.
I'm limited to C++11, but Boost is available.

First of all, relying on a global variable is not a really good idea, because it will give wrong results if you call readFile while a previous read is still in progress. So you really should encapsulate that whole reading process in a class.
You need to use a lambda or std::bind because the parameters of callback are not known outside of the fileMgr_ReadWithCallback function.
So you create a wrapping callback accepting a std::string as a parameter. And use a lambda to capture the parameters, the lambda accepts a string as a parameter, and passes the string and the params to the callback:
storage = [=](std::string s) {
callback(s, params...);
};
And that's how the code then could look like (but as I already said that's bad design)
#include <functional>
#include <iostream>
std::function<void(std::string)> storage;
void fileMgr_DoneWithOtherstuff_DoTheReads() {
std::string result = "CONTENT";
storage(result);
}
template<class ReadFileCallback, class ...T>
void fileMgr_ReadWithCallback(std::string filename, ReadFileCallback callback, T ...params) {
std::cout << "fileMgr_ReadWithCallback is processing file: " << filename << std::endl;
storage = [=](std::string s) {
callback(s, params...);
};
}
void readFileResult(std::string contents, int id) {
std::cout << "readFileResult callback: contents=" << contents << ", id=" << id << std::endl;
}
void readFile(std::string filename, int id) {
fileMgr_ReadWithCallback(filename, readFileResult, id);
}
int main()
{
int fileId = 1;
readFile("myfile", fileId);
fileMgr_DoneWithOtherstuff_DoTheReads();
return 0;
}

You could store your parameters in a tuple via auto storedParams = std::make_tuple(params...). And later you can call your callback function simply with std::apply(callback, storedParams ).
To add an additional parameter (like content) you can use std::tuple_cat(std::make_tuple(content), storedParams ).
I would store the parameters and the callback separately.
BTW: std::apply is only available with C++17 - is there something to emulate that (perhaps in boost)? Otherwise I would try to use the implmentations for std::invoke and std::apply which are shown on cppreference (just remove constexpr...).
Here you can find the code: https://godbolt.org/z/z9MP3M
But you need to add std::apply (that is the most difficult part). Why you need to use such an old compiler?
Update
Perhaps you could use the type erasure features of std::function, see here:
#include <iostream>
#include <string>
#include <functional>
static std::function<void(std::string)> fileManagerStorage;
void fileMgr_DoneWithOtherstuff_DoTheReads() {
//FROM SOMESTORAGE get the callback and params
//Do the reading
std::string content = "CONTENT";
fileManagerStorage(content);
//Call the callback with result string and params
fileManagerStorage(content);
}
template<class ReadFileCallback, class ...T>
void fileMgr_ReadWithCallback(std::string filename, ReadFileCallback callback, T ...params) {
std::cout << "fileMgr_ReadWithCallback is processing file: " << filename << std::endl;
// string content = "CONTENT";
// callback(content, params...);
fileManagerStorage = [=](std::string content){
callback(content, params...);
};
}
void readFileResult(std::string contents, int id) {
std::cout << "readFileResult callback: contents=" << contents << ", id=" << id << std::endl;
}
void readFile(std::string filename, int id) {
fileMgr_ReadWithCallback(filename, readFileResult, id);
}
int main()
{
int fileId = 1;
readFile("myfile", fileId);
return 0;
}
(You should store the storage not as a global variable - store it in your thread...)

Related

c++ callbacks to another member function

I have a question on callbacks. Previously, I am associating my callbacks to a class Q
class Q{
using Callback = std::function<void(char*, int)>;
Q:Q();
Q:~Q();
void Q::RegisterCB(Callback callbackfunc)
{
callback_func = callbackfunc;
}
void Q:someEvent()
{
callback_func();
}
};
void handleCallback( char*, int)
{
// perform some routine
}
// from my main file
int main()
{
Q q;
q.RegisterCB(&handleCallback);
}
It works well for me. However, when I need to transfer the handleCallback function to another class for cleaner code. I have problem with using same code
class R{
void R::handleCallback( char*, int)
{
// perform some routine
}
void R::someOp()
{
// q is some member variables of R
q.RegisterCB(&R::handleCallback, this);
}
};
However, i run into some problems of saying there is a "no matching function for call to .....". I thought it was just simply assigning from function name to class function name
May I have a hint to where I might go wrong?
Regards
&R::handleCallback has the type void (R::*)(char*, int), which is not convertible to std::function<void(char*, int)>.
Also, RegisterCB takes one argument, not two.
The most straightforward fix is to wrap the call in a lambda function,
q.RegisterCB([this](char* p, int x) { handleCallback(p, x); });
Example on how to use a lambda function to register a member function of an instance of R as event handler. (I replaced char* with string_view out of habit, it's not essential for this example). The use of "const" wherever you can is a recommendation.
#include <functional>
#include <string_view>
#include <iostream>
class Q
{
public:
// use const arguments, the callback is not supposed to change them
// just passing information on to callback
using callback_t = std::function<void(const std::string_view&, const int)>;
// initialize callback with a (lambda) function that does nothing
// this prevents the need for a check if callback has been set or not
// (Pattern : Null Strategy)
Q() :
m_callback_func( [](const std::string_view&,const int) {} )
{
}
~Q() = default;
void RegisterCallback(callback_t fn)
{
m_callback_func = fn;
}
void Event(const std::string_view& string, const int value)
{
m_callback_func(string,value);
}
private:
callback_t m_callback_func;
};
void handleCallback(const std::string_view& string, const int value)
{
std::cout << string << ", " << value << "\n";
}
class R
{
public:
void handleCallback(const std::string_view& string, const int value)
{
std::cout << string << ", " << value << "\n";
}
};
// from my main file
int main()
{
Q q1;
q1.RegisterCallback(handleCallback);
q1.Event("Hello", 42);
// to pass a callback to an instance of a class
// you can use a lambda function https://en.cppreference.com/w/cpp/language/lambda
R r;
Q q2;
q2.RegisterCallback([&r](const std::string_view& string, const int value)
{
r.handleCallback(string,value);
});
q2.Event("World",21);
return 0;
}

How can I pass a member function with an unknown prototype to a class in C++?

I need to make a class (we'll call it Command) that takes in a string, processes it into function arguments, and then passes it to a member function of a different class. For my use, the member function that I pass to Command could come from a number of classes, and could have many different prototypes. I can guarantee that that member function will return void. Here's the code I imagine:
class Command {
public:
vector<tuple<int, string, any>> argument_specification;
SomeType callable;
Command(vector<tuple<int, string, any>> argument_spec, SomeType callable) {
this->argument_specification = argument_spec;
this->callable = callable;
}
void apply(string args) {
/* processing args according to this->argument_specification
to make a std::tuple arguments */
std::apply(this->callable, arguments);
}
};
class Action {
public:
print_two_arguments(int arg1, int arg2) {
std::cout << arg1 << ", " << arg2 << std::endl;
}
print_one_arguments(std::string arg1) {
std::cout << arg1 << std::endl);
}
}
int main() {
Action *actor = new Action();
// my argument specification code splits by string and then extracts
// arguments by position or keyword and replacing with a default if
// not specified
Command *command1 = new Command({{0, "first_arg", "something"}},
&actor->print_one_argument);
command1->apply("hello_world"); // Should print "hello_world"
Command *command2 = new Command({{0, "first_arg", 2},
{1, "second_arg", 10}},
&actor->print_two_arguments);
command2->apply("0 2"); // should print "0 2"
}
I don't really mind what method gets there - I've tried std::bind and can't quite get that to work, I've also tried lambdas. I'm currently trying a template class with a type deduced factory method. I'm also open to a macro definition that will fix this at compile time.
A couple ideas come to mind, but the key thing that I'm seeing is that you want to be able to take an arbitrary void function and call it with a single string. Templates can be really helpful here because you can use them to auto-deduce things such as how to build the tuple that you apply to the function.
This will be a semi-complicated meta-program-y solution, but I love that stuff; so I'm going to build a prototype. Also beware, this is the kind of solution that will result in absolutely horrendous compiler errors if you try to use it wrong.
My suggestion would be to make Command a templated type, where the command itself is templated on the parameter types of the function you want to pass it. If you need to be able to make a list of these to apply arguments to, then you can have a base class which provides the apply function. Since I don't fully understand how the argument specification is supposed to work, I'm punting on that and supporting keyword arguments only; but the way I built this, it should be fairly straightfoward to sub in your own argument splitter. I think. It could be cleaner, but I need to get back to my job.
Play with it on Compiler Explorer: https://godbolt.org/z/qqrn9bs1T
#include <any>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <memory>
#include <regex>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
// Converts the string arguments to the actual types
template <class T> T convert_arg(std::string);
template <> std::string convert_arg<std::string>(std::string s) { return s; }
template <> int convert_arg<int>(std::string s) { return std::stoi(s); }
// Split on spaces
std::vector<string> tokenize(std::string s) {
istringstream iss(s);
return {istream_iterator<string>{iss}, istream_iterator<string>{}};
}
// Argument spec defines how to parse the arguments from the input. It
// contains the positional index in the string, the name of it, and a
// default value. It's effectively a mapping from the string being applied
// to the function being called.
//
// This could maybe be turned into a std::tuple<std::tuple<...>>, but
// I'm not sure. That could get a little messy with trying to iterate
// through it to build the argument list, and I don't think it buys us
// anything.
//
// For example, given the argument spec
// {{1, "first_arg", 0}, {0, "second_arg", "some_default"}}
// You could call a function that has the signature
// void (int, string);
// And you could parse the following argument strings (assuming space-delimited)
// "second_arg=hello first_arg=0"
// "words 1"
// "first_arg=5 more_text"
using argument_spec_t = std::vector<tuple<std::size_t, string, std::string>>;
class CommandBase {
public:
virtual void apply(string args) = 0;
};
// Concrete commands are templated on the argument types of the function
// that they will invoke. For best results, use make_command() to deduce
// this template from the function that you want to pass the Command in
// order to get references and forwarding correct.
template <class... ArgTs> class Command : public CommandBase {
public:
using callable_t = std::function<void(ArgTs...)>;
// Holds the argument specification given during constuction; this
// indicates how to parse the string arguments
argument_spec_t m_argument_specification;
// A function which can be invoked
callable_t m_callable;
Command(argument_spec_t argument_spec, callable_t callable)
: m_argument_specification(std::move(argument_spec)),
m_callable(std::move(callable)) {}
void apply(string args) {
//std::cout << "Apply " << args << std::endl;
std::tuple parsed_args =
build_args(split_args(std::move(args), m_argument_specification),
std::index_sequence_for<ArgTs...>{});
std::apply(m_callable, parsed_args);
}
private:
// Pre-processes the command arguments string into a
// std::unordered_map<size_t, std::string> where x[i] returns the text of the
// i'th argument to be passed to the function.
//
// \todo Support positional arguments
// \todo Be more robust
static std::unordered_map<size_t, std::string>
split_args(std::string args, const argument_spec_t &arg_spec) {
std::unordered_map<std::string, std::string> kw_args;
std::unordered_map<size_t, std::string> arg_map;
vector<string> tokens = tokenize(args);
for (const auto &token : tokens) {
auto delim = token.find("=");
auto key = token.substr(0, delim);
auto val = token.substr(delim + 1);
kw_args[key] = val;
// std::cout << "key = " << val << std::endl;
}
for (size_t i = 0; i < arg_spec.size(); ++i) {
const auto &[pos_index, key, default_val] = arg_spec[i];
auto given_arg_it = kw_args.find(key);
if (given_arg_it != kw_args.end())
arg_map[i] = given_arg_it->second;
else
arg_map[i] = default_val;
// std::cout << i << " -> " << arg_map[i] << std::endl;
}
return arg_map;
}
// Copies the arguments from the map returned by pre_process_args into a
// std::tuple which can be used with std::apply to call the internal function.
// This uses a faux fold operation because I'm not sure the right way to do a
// fold in more modern C++
// https://articles.emptycrate.com/2016/05/14/folds_in_cpp11_ish.html
template <std::size_t... Index>
std::tuple<ArgTs...>
build_args(std::unordered_map<size_t, std::string> arg_map,
std::index_sequence<Index...>) {
std::tuple<ArgTs...> args;
std::initializer_list<int> _{
(std::get<Index>(args) =
convert_arg<std::tuple_element_t<Index, std::tuple<ArgTs...>>>(
std::move(arg_map[Index])),
0)...};
return args;
}
};
// Factory function to make a command which calls a pointer-to-member
// function. It's important that the reference to the object stays in
// scope as long as the Command object returned!
template <class C, class... ArgTs>
std::unique_ptr<CommandBase> make_command(C &obj,
void (C::*member_function)(ArgTs...),
argument_spec_t argument_spec) {
return std::make_unique<Command<ArgTs...>>(
std::move(argument_spec), [&obj, member_function](ArgTs... args) {
(obj.*member_function)(std::forward<ArgTs>(args)...);
});
}
// Factory function to make a command which calls a std::function.
template <class... ArgTs>
std::unique_ptr<CommandBase>
make_command(std::function<void(ArgTs...)> callable,
argument_spec_t argument_spec) {
return std::make_unique<Command<ArgTs...>>(std::move(argument_spec),
std::move(callable));
}
// Factory function to make a command which calls a free function
template <class... ArgTs>
std::unique_ptr<CommandBase> make_command(void (*fn)(ArgTs...),
argument_spec_t argument_spec) {
return make_command(std::function<void(ArgTs...)>{fn},
std::move(argument_spec));
}
class Action {
public:
void print_two_arguments(int arg1, int arg2) {
std::cout << arg1 << ", " << arg2 << std::endl;
}
void print_one_argument(std::string arg1) { std::cout << arg1 << std::endl; }
};
void print_one_argument_free(std::string arg1) {
std::cout << arg1 << std::endl;
}
int main() {
Action actor;
// my argument specification code splits by string and then extracts
// arguments by position or keyword and replacing with a default if
// not specified
auto command1 = make_command(actor, &Action::print_one_argument,
argument_spec_t{{0, "first_arg", "something"}});
command1->apply("first_arg=hello_world"); // Should print "hello_world"
auto command2 = make_command(
actor, &Action::print_two_arguments,
argument_spec_t{{0, "first_arg", "2"}, {1, "second_arg", "10"}});
command2->apply("0 second_arg=2"); // should print "0 2"*/
auto command3 = make_command(&print_one_argument_free,
argument_spec_t{{0, "first_arg", "something"}});
command3->apply("first_arg=hello_again");
}
I think there are a number of ways to handle this problem, including function pointers with variable arguments, etc. But your fundamental problem is that you're asking one class to understand the internals of another class, which never works out well. I'd argue instead that you should have a parent Actor class that has a function that can be overridden by sub-classes and just passing an instance of the subclass instead. Each subclass may need to take an array of arguments, or even another container type that each subclass knows what it needs from within.
#include <iostream>
using namespace std;
class Data {
public:
std::string strdata;
int intinfo1;
int intinfo2;
};
class ActionBase {
public:
virtual void act(Data d) = 0;
};
class PrintIntinfos : public ActionBase {
public:
virtual void act(Data d) {
std::cout << d.intinfo1 << ", " << d.intinfo2 << std::endl;
}
};
class PrintStrData : public ActionBase {
public:
virtual void act(Data d) {
std::cout << d.strdata << std::endl;
}
};
int main()
{
ActionBase *Action1 = new PrintIntinfos();
Data d = Data();
d.intinfo1 = 42;
d.intinfo2 = -42;
Action1->act(d);
delete Action1;
d.strdata = "hello world";
Action1 = new PrintStrData();
Action1->act(d);
}
What you should actually do requires analysis of what your goals are with respect to base-pointers and containers and your data structure, flow, etc.
In your apply you describe something that really wants the context of the constructor. What if Command was
class Command {
std::function<void(std::string)> callable;
public:
template <typename... Args>
Command(std::function<std::tuple<Args...>(std::string)> argument_spec, std::function<void(Args...)> callable)
: callable([=](std::string args) { std::apply(callable, argument_spec(args)); })
{ }
void apply(std::string args) {
callable(args);
}
};
You would still be able to use your argument specification code to create the argument_spec parameter

Passing a member function of another class into a std::function parameter

I have a class with a function that takes a std::function and stores it. This part seems to compile ok (but please point out any issue if there are any)
#include <functional>
#include <iostream>
struct worker
{
std::function<bool(std::string)> m_callback;
void do_work(std::function<bool(std::string)> callback)
{
m_callback = std::bind(callback, std::placeholders::_1);
callback("hello world\n");
}
};
// pretty boring class - a cut down of my actual class
struct helper
{
worker the_worker;
bool work_callback(std::string str)
{
std::cout << str << std::endl;
return true;
}
};
int main()
{
helper the_helper;
//the_helper.the_worker.do_work(std::bind(&helper::work_callback, the_helper, std::placeholders::_1)); // <---- SEGFAULT (but works in minimal example)
the_helper.the_worker.do_work(std::bind(&helper::work_callback, &the_helper, std::placeholders::_1)); // <---- SEEMS TO WORK
}
I get a segfault, but I am not sure why. I have used this before, in fact, I copied this example from another place I used it. The only real difference that the member function was part of the class I called it from (i.e. this instead of the_helper).
So this is why I am also asking if there is anything else I am doing wrong in general? Like should I be passing the std::function as:
void do_work(std::function<bool(std::string)>&& callback)
or
void do_work(std::function<bool(std::string)>& callback)
As also noted by #Rakete1111 in comments, the problem probably was in this code:
bool work_callback(std::string str)
{
std::cout << str << std::endl;
}
In C++ if a non-void function does not return a value the result is undefined behavior.
This example will crash with clang but pass with gcc.
If helper::work_callback returns (e.g, true) the code works just fine.
I don't know why your code seg faults because I was spoiled and skipped std::bind straight to lambdas. Since you use C++11 you should really convert your code from std::bind to lambdas:
struct worker
{
std::function<bool(std::string)> m_callback;
void do_work(std::function<bool(std::string)> callback)
{
m_callback = callback;
callback("hello world\n");
}
};
Now with work_callback and calling do_work things need some analysis.
First version:
struct helper
{
worker the_worker;
bool work_callback(std::string)
{
return false;
}
};
int main()
{
helper the_helper;
the_helper.the_worker.do_work([&](std::string s) { return the_helper.work_callback(s); });
}
Now this version works with your toy example. However out in the wild you need to be careful. The lambda passed to do_work and then stored in the_worker captures the_helper by reference. This means that this code is valid only if the helper object passed as reference to the lambda outlives the worker object that stores the m_callback. In your example the worker object is a sub-object of the the helper class so this is true. However if in your real example this is not the case or you cannot prove this, then you need to capture by value.
First attempt to capture by value (does not compile):
struct helper
{
worker the_worker;
bool work_callback(std::string)
{
return false;
}
};
int main()
{
helper the_helper;
the_helper.the_worker.do_work([=](std::string s) { return the_helper.work_callback(s); });
}
This does not compile because the copy of the_helper stored in the lambda object is const by default and as such you cannot call work_callback on it.
A questionable solution if you can't make work_callback const is to make the lambda mutable:
struct helper
{
worker the_worker;
bool work_callback(std::string)
{
return false;
}
};
int main()
{
helper the_helper;
the_helper.the_worker.do_work([=](std::string s) mutable { return the_helper.work_callback(s); });
}
But you need to think if this is what you intended.
What would make more sense is to make work_callback const:
struct helper
{
worker the_worker;
bool work_callback(std::string) const
{
return false;
}
};
int main()
{
helper the_helper;
the_helper.the_worker.do_work([=](std::string s) { return the_helper.work_callback(s); });
}
The reason for getting SEGFAULT has been already mentioned in the comments.
However, I would like to point out that, you need to use neither std::bind nor std::function, here in your given case. Instead, simply having a lambda and a function pointer you can handle what you intend to do.
struct worker
{
typedef bool(*fPtr)(const std::string&); // define fun ptr type
fPtr m_callback;
void do_work(const std::string& str)
{
// define a lambda
m_callback = [](const std::string& str)
{
/* do something with string*/
std::cout << "Call from worker: " << str << "\n";
return true;
};
bool flag = m_callback(str);// just call the lambda here
/* do some other stuff*/
}
};
struct helper
{
worker the_worker;
bool work_callback(const std::string& str)
{
std::cout << "Call from helper: ";
this->the_worker.do_work(str);
return true; ------------------------>// remmeber to keep the promise
}
};
And use case would be:
int main()
{
helper the_helper;
the_helper.work_callback(std::string("hello world"));
// or if you intend to use
the_helper.the_worker.do_work(std::string("hello world"));
return 0;
}
see Output here:
PS: In the above case, if worker does not required m_callback for later cases(i.e, only for do_work()), then you can remove this member, as lambdas can be created and called at same place where it has been declared.
struct worker
{
void do_work(const std::string& str)
{
bool flag = [](const std::string& str)->bool
{
/* do something with string*/
std::cout << "Call from worker: " << str << "\n";
return true;
}(str); -------------------------------------> // function call
/* do other stuff */
}
};

How emulate a templatised std::function in C++

Following is a basic instance of what I am doing in my C++ program. I have a list of listeners which are all std::functions. I have a concept DataType which means what kind of data the listener is interested in. The idea here is the same as publish-subscribe pattern. A method interested in certain kind of data should be able to add itself to the list of listeners using AddListener. Some methods are added & they receive a callback whenever required.
The program works fine !!
#include <iostream>
#include <functional>
#include <vector>
#include <string>
enum class DataType {
Type_1,
Type_2
// and so on
};
typedef std::function<void(std::pair<DataType, std::string>)> MyListenerType;
//template <typename T>
//typedef std::function<void(T>)> MyListenerType;
// How can I emulate the above so that a method passing any kind of primitive data-type namely "int, bool, float or double" can be added into
// my vector of listners.
std::vector<MyListenerType> my_data_listeners_1;
std::vector<MyListenerType> my_data_listeners_2;
void ListenerMethod_Instance_1(std::pair<DataType, std::string> information) {
DataType data_type = information.first;
std::string message = information.second;
std::cout << "ListenerMethod_Instance_1 called with message " << message << "\n";
}
void ListenerMethod_Instance_2(std::pair<DataType, std::string> information) {
DataType data_type = information.first;
std::string message = information.second;
std::cout << "ListenerMethod_Instance_2 called with message " << message << "\n";
}
void AddListener (MyListenerType listener, DataType type_of_interest) {
if (DataType::Type_1 == type_of_interest) {
my_data_listeners_1.push_back(listener);
std::cout << "Added a method instance for DataType::Type_1" << "\n";
}
else if (DataType::Type_2 == type_of_interest) {
my_data_listeners_2.push_back(listener);
std::cout << "Added a method instance for DataType::Type_2" << "\n";
}
else {
std::cout << "Listener type not supported" << "\n";
}
}
void CallAllListnersWhohaveSuscribed() {
if (!my_data_listeners_1.empty()) {
std::string send_message_1 = "some message 123";
std::pair <DataType, std::string> info_to_send_1 = std::make_pair (DataType::Type_1, send_message_1);
for(auto const &listener : my_data_listeners_1) {
listener(info_to_send_1);
}
}
if (!my_data_listeners_2.empty()) {
std::string send_message_2 = "some message 456";
std::pair <DataType, std::string> info_to_send_2 = std::make_pair (DataType::Type_2, send_message_2);
for(auto const &listener : my_data_listeners_2) {
listener(info_to_send_2);
}
}
}
int main() {
// Add ListenerMethod_Instance_1 for instance
DataType data_type_1 = DataType::Type_1;
auto listener_instance_1 = std::bind(ListenerMethod_Instance_1, std::placeholders::_1);
AddListener(listener_instance_1, data_type_1);
// Add ListenerMethod_Instance_2 for instance
DataType data_type_2 = DataType::Type_2;
auto listener_instance_2 = std::bind(ListenerMethod_Instance_2, std::placeholders::_1);
AddListener(listener_instance_2, data_type_2);
CallAllListnersWhohaveSuscribed();
return 0;
}
Following is the output of the program:
./stdFunctionTest
Added a method instance for DataType::Type_1
Added a method instance for DataType::Type_2
ListenerMethod_Instance_1 called with message some message 123
ListenerMethod_Instance_2 called with message some message 456
But here is how I want to modify & struggling with. The caveat is that every ListenerMethod_Instance_1 & ListenerMethod_Instance_2 have to parse the pair to get their info which I don't want to. I want to enable a method of any C++ primitive data type be it "int, bool, float or double" to be able to be added into the listeners vector & receive the callback. For example following method should be "add-able" into AddListener.
void ListenerMethod_Instance_3(int integer_data) {
std::cout << "ListenerMethod_Instance_3 called with integer_data " << integer_data << "\n";
}
Looking at this link here looks somewhat possible someway. But I'm struggling to adapt it to my use-case here. Please suggest.
So, basically how can I achieve templates functionality with std::functions ?
struct anything_view_t {
void* ptr=0;
template<class T, std::enable_if_t<!std::is_same<anything_view_t, std::decay_t<T>>{}, int> =0>
anything_view_t(T&&t):ptr(std::addressof(t)){}
anything_view_t()=default;
anything_view_t(anything_view_t const&)=default;
anything_view_t& operator=(anything_view_t const&)=default;
template<class T>
operator T() const { return *static_cast<T*>(ptr); }
};
this is a very unsafe type erasing view of anything.
struct any_callbacks {
std::unordered_map<std::type_index, std::vector<std::function<void(anything_view_t)>>> table;
template<class T>
void add_callback( std::function<void(T)> f ){
table[typeid(T)].push_back(f);
}
template<class T>
void invoke_callbacks(T t) const {
auto it = table.find(typeid(T));
if (it==table.end()) return;
for(auto&&f:it->second)
f(t);
}
};
something like the above should work. The type T must match exactly. References not supported. Code not compiled, design is sound, probably has typos.
This is not restructed to primitive types. You should pass T explicitly, don't rely on deduction as that is fragile.

Add function reference to list

My question is rather simple, however i was unable to find anything about it on google (possibly because i am new to c++ and don't quite know the right terminology for everything yet). My question is, is it possible for me to add a reference to a function in a list, and if so, what is the correct way to do it?
Basically what i'm trying to do is to create an event class that would be able to store function references in a list so that i could do some basic event handling.
What im thinking of doing is something like this:
list<function> fnlist;
void add(function fn) {
fnlist.add(fn);
}
void call() {
for (function &fn: fnlist) {
fn();
}
}
Is something like this possible?
Please note that i would like to avoid using any event libraries if i could do this without any.
Absolutely, this is possible:
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
void quick() {
cout << "quick ";
}
void brown() {
cout << "brown ";
}
void fox() {
cout << "fox ";
}
int main() {
vector<function<void()> > events;
events.push_back(quick);
events.push_back(brown);
events.push_back(fox);
for (auto f : events) {
f();
}
return 0;
}
Use std::function<void()> to hold a functional object that encapsulates a callable that takes no parameters, and does not return a result.
Demo.
Use following :
/* ret_type : Return Type,
arg_type - type of argument (can be multiple, separated by comma)
*/
typedef std::function<ret_type( arg_type )> function ;
std::list < function> fnlist ;
void add(function fn)
{
fnlist.add(fn);
}
void call()
{
for (const auto &fn: fnlist)
{
fn();
}
}