using boost::function with instance methods - c++

I am trying to use boost::function with instance methods using the following example
class someclass
{
public:
int DoIt(float f, std::string s1)
{
return 0;
}
int test(boost::function<int(float, std::string)> funct)
{
//Funct should be pointing to DoIt method here
funct(12,"SomeStringToPass");
}
void caller()
{
test(DoIt); //Error : 'someclass::DoIt': function call missing argument list; use '&someclass::DoIt' to create a pointer to member
}
};
Any suggestion on how I could resolve this issue ?

You should use boost::bind:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <string>
#include <iostream>
using namespace std;
class someclass
{
public:
int DoIt(float f, std::string s1)
{
return 0;
}
int test(boost::function<int(float, std::string)> funct)
{
return funct(5.0, "hello");
}
void caller()
{
cout << test(boost::bind(&someclass::DoIt, this, _1, _2)) << endl;
}
};
int main() {
someclass s;
s.caller();
}

Related

How access class functions with <future> library?

I'm trying to make a program with #include <future> library.
When I try to access a header function, I get an error.
no instance of overloaded function "async" matches the argument list -- argument types are: (std::launch, int ()) [line 16, 14]
a pointer to a bound function may only be used to call the function
[line 16, 37]
main.cpp:
#include "TEST.h"
#include <future>
#include <iostream>
using namespace std;
using namespace Class;
FNH f;
int main(){
auto fn = async(launch::async, f.selam);
}
TEST.h:
#pragma once
#include <iostream>
using namespace std;
namespace Class{
class FNH{
public:
int selam(){
cout << "selam";
return 1;
}
};
}
I'm a beginner at coding so I really don't know how to fix it or if it's possible.
You can pass a member function pointer and the instance of the class it will be called on:
#include <future>
#include <iostream>
namespace Class {
class FNH {
public:
int selam(){
std::cout << "selam";
return 1;
}
int selam_2(int a, int b){
std::cout << "selam "<< a << " " << b;
return 1;
}
};
}
int main(){
Class::FNH f;
// Member Function Pointer
auto fn = std::async(std::launch::async, &Class::FNH::selam, f);
// Member Function Pointer with arguments
auto fn2 = std::async(std::launch::async, &Class::FNH::selam_2, f, 1, 2);
}
Put the method call in a lambda
#include <future>
#include <iostream>
namespace Class{
class FNH {
public:
int selam(){
std::cout << "selam";
return 1;
}
};
}
int main(){
Class::FNH f;
auto fn = std::async(std::launch::async, [&f]{ return f.selam(); });
}

how transfer function from template class

#include <iostream>
#include <windows.h>
#include <string.h>
#include <functional>
#include <stdint.h>
#include <stdio.h>
using namespace std;
template <typename T>
class someclass {
public:
T value;
int sum(int vl1, int vl2) { return vl1 + vl2; };
};
template <typename T>
class someclass2 {
public:
T value;
void print(const std::function<int(int, int)>& func) {
cout << func(3, 4) << '\n';
};
};
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
obj2.print(obj1.sum);
}
Compiler show error on last line : error C3867: 'someclass::sum': non-standard syntax; use '&' to create a pointer to member
Note that
int sum(int vl1, int vl2) { return vl1 + vl2; };
doesn't use its owner class' member in any way, it safely can be declared static, in that case this code would work.
The problem with this code is that a member function got a different type from standalone function. It's a member of class someclass, so its type is int (someclass::*)(int, int) and to call it you need an instance of that class.
The literal solution in general case is to hide pass of this inside the functor created by lambda expression:
obj2.print( [&](int a, int b)-> int { return obj1.sum(a,b); } );
You can use std::bind to do that
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
using namespace std::placeholders;
obj2.print(std::bind(&someclass<int>::sum, &obj1, _1, _2));
}

Calling a method from one class in another class

I have this class:
boer.h
#pragma once
#include <functional>
#include <iostream>
class boer
{
private:
std::function<void(int id_)> someFun;
public:
boer();
~boer();
void setSomeFun(std::function<void(int id_)> someFun_);
void getSomeFun();
};
boer.cpp
#include "boer.h"
boer::boer() { }
boer::~boer() { }
void boer::setSomeFun(std::function<void(int id_)> someFun_)
{
someFun = someFun_;
}
void boer::getSomeFun()
{
someFun(12345);
}
And this class:
aircraft.h
#pragma once
#include <functional>
#include <iostream>
#include "boer.h"
class aircraft
{
private:
boer Boer;
public:
aircraft();
~aircraft();
void source_forSomeFun(int id_);
};
aircraft.cpp
#include "aircraft.h"
aircraft::aircraft() { }
aircraft::~aircraft() { }
void aircraft::source_forSomeFun(int lol_)
{
std::cout << "AMAZING!!!" << std::endl;
}
And I need to connect void source_forSomeFun(int id_); in aicraft with std::function<void(int id_)> someFun; in boer. How can I do this? Maybe there is another way, but i think this method is the most preferable.
int main()
{
aircraft Aircraft;
boer Boer;
Boer.setSomeFun(???); // here
Boer.getSomeFun();
int i;
std::cin >> i;
return 0;
}
Boer.setSomeFun([&](int v){aircraft.source_forSomeFun(v);});
Use a lambda.

Call a member function using for_each

This was my original code
#include "stdafx.h"
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class testing
{
public:
int value;
testing(int v)
{
value = v;
}
int getval()
{
return(value);
}
};
void func(testing& ob)
{
printf("The value is %d\n", ob.value);
}
int _tmain(int argc, _TCHAR* argv[])
{
std::list<testing> testvar[3];
testing t1(0);
testing t2(1);
testing t3(3);
testvar[0].push_back(t1);
testvar[0].push_back(t2);
testvar[0].push_back(t3);
std::for_each(testvar[0].begin(), testvar[0].end(), func);
printf("Reached End");
getchar();
return 0;
}
I modified it to make func a member function and got weird compile errors, I searched online and someone had told use bind1st, bind2nd
#include "stdafx.h"
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class testing
{
public:
int value;
testing(int v)
{
value = v;
}
int getval()
{
return(value);
}
};
class testing2
{
public:
std::list<testing> testvar[3];
void func(testing& ob)
{
printf("The value is %d\n", ob.value);
}
void driver()
{
std::for_each(testvar[0].begin(), testvar[0].end(), func);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
testing2 testob;
testob.driver();
printf("Reached End");
getchar();
return 0;
}
So I modified the driver function to this
void driver()
{
std::for_each(testvar[0].begin(), testvar[0].end(), std::bind1st(std::mem_fun(&testing2::func), this));
}
I still get some weird compile erros, could someone please expain why we need to call a member function is such weird way..? and how does bind1st help..?
Use std::bind
std::for_each(testvar[0].begin(), testvar[0].end(), std::bind(&testing2::func, this, std::placeholders::_1));
Or use std::bind/lambdas
std::for_each(testvar[0].begin(), testvar[0].end(), [this](testing& ob) { func(ob); });
Full:
#include <string>
#include <list>
#include <algorithm>
using namespace std;
struct testing {
int value;
testing(int v) { value = v; }
int getval() { return(value); }
};
struct testing2 {
std::list<testing> testvar[3];
void func(testing& ob) {
printf("The value is %d\n", ob.value);
}
void driver() {
auto f = std::bind(&testing2::func, this, std::placeholders::_1);
std::for_each(testvar[0].begin(), testvar[0].end(), f);
std::for_each(testvar[0].begin(), testvar[0].end(), [this](testing& ob) { func(ob); });
}
};
int main() {
testing2 testob;
testob.driver();
printf("Reached End");
}
You can also use std::mem_fn for cleaner syntax like this:
std::for_each(testvar[0].begin(), testvar[0].end(), std::mem_fn(&testing::func));
Complete code:
#include <stdio.h>
#include <bits/stdc++.h>
class testing
{
public:
testing(int v) : value(v) {}
int getval() {
return(value);
}
void func()
{
printf("The value is %d\n", value);
}
private:
int value;
};
int main() {
std::list<testing> testvar[3];
testing t1(0);
testing t2(1);
testing t3(3);
testvar[0].push_back(t1);
testvar[0].push_back(t2);
testvar[0].push_back(t3);
std::for_each(testvar[0].begin(), testvar[0].end(), std::mem_fn(&testing::func));
return 0;
}

Passing string as reference to function pointer c++

Below is my code
#include "stdafx.h"
#include <string.h>
#include <iostream.h>
using namespace std;
class ToDoCommands
{
public:
void getCommand(string);
};
void ToDoCommands::getCommand(string command)
{
cout<<command; //here i get ping
void (*CommandToCall)(void);
CommandToCall = command; // error here i want something like
// CommandToCall = ping
CommandToCall();
}
void ping(void)
{
cout<<"ping command executed";
}
int main()
{
ToDoCommands obj;
obj.getCommand("ping");
}
The function pointer should refer to function ping dynamically. A string same as function name is passed to getCommand function in main.
C++ just doesn't work that way. If you really need something like that, you'll have to make a table of functions that are indexed by name:
#include <assert.h>
#include <iostream>
#include <map>
#include <string>
using std::cout;
using std::string;
using std::map;
void ping(void)
{
cout << "ping command executed\n";
}
class ToDoCommands
{
public:
typedef void (*FunctionPtr)();
typedef string Name;
void registerFunction(Name name,FunctionPtr);
void callFunction(Name);
private:
map<Name,FunctionPtr> func_map;
};
void ToDoCommands::registerFunction(Name name,FunctionPtr func_ptr)
{
func_map[name] = func_ptr;
}
void ToDoCommands::callFunction(Name name)
{
assert(func_map.find(name)!=func_map.end());
func_map[name]();
}
int main(int argc,char **argv)
{
ToDoCommands to_do_commands;
to_do_commands.registerFunction("ping",ping);
to_do_commands.callFunction("ping");
return 0;
}
void ping(void)
{
// LL DD…DD XX
cout<<"ping command executed"<<endl;
}
class ToDoCommands
{
public:
void getCommand( void (*CommandToCall)(void)); //getCommand(ping)
};
void ToDoCommands::getCommand( void (*CommandToCall)(void) )
{
void (*CommandToCall1)(void);
CommandToCall1 = CommandToCall;
CommandToCall1();
}
int main()
{
ToDoCommands obj;
obj.getCommand( ping );
return 0;
}
i tried this and its working :)