Compile Errors in Class with User Defined Functions - class

I am trying to build a class that stores a user-defined function inside of it for later use. I have decided to use the boost::function object to do so.
However, I get the following error on compile:
error: no match for ‘operator=’ in ‘((SomeClass*)this)->SomeClass::someFunction = ((SomeClass*)this)->SomeClass::DefaultFunction’
I do not understand this error, since someFunction and DefaultFunction should, as far as I can see, have the same types.
The code is shown below:
#include <boost/function.hpp>
class SomeClass{
private:
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
public:
SomeClass();
~SomeClass();
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=DefaultFunction;
}
~SomeClass::SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
void MyProgram(){
SomeClass s;
}
Can anyone offer any pointers as to how to construct such an object? Alternatively, iff there is a better way than the one I am attempting, could you explain it to me?
Kindest regards!

DefaultFunction is a member function of SomeClass.
Member function is called for some instance of SomeClass.
This function takes "hidden" pointer to SomeClass instance as its first parameter addition to int.
So member function is not the same as free function.
Your someFunction is object of boost::function, so it is wrapper for callable object.
Your requirements to that object are: take int and returns int.
In order to assign DefaultFunction (as member function) to someFunction you need to create this callable object.
Here you need to specify for which instance of SomeClass this object will be called, to do that use boost::bind:
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, boost::placeholders::_1);
}
In the code above you create callable object which will behave as
struct unnamedClass {
SomeClass* sc;
unnamedClass (SomeClass* sc) : sc(sc) {} // here sc is this of SomeClass
int operator()(int arg)
{
return sc->DefaultFunction(arg);
}
};
so when you invoke someFunction(10) it takes 10 as argument and call DefaultFunction for current this instance.
This
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
works because f is free function, which takes no hidden - pointer to class instance.

Using the answer of #rafix07, the following code compiled:
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/bind/placeholders.hpp>
class SomeClass{
private:
public:
SomeClass();
~SomeClass();
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, _1);
}
SomeClass::~SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
int MyOwnProgram(int i){
return i+2;
}
void MyProgram(){
SomeClass s;
std::cout<<s.someFunction(2)<<std::endl;
s.SetFunction(MyOwnProgram);
std::cout<<s.someFunction(2)<<std::endl;
}
int main()
{
MyProgram();
}
The output from the program is:
3
4

Related

what is the correct syntax function pointer list with class member?

I have a list of function pointers, the non-class member compiles without errors, but the class member compiles with errors:
error: cannot convert 'void (CVdmConfig::)()' to 'fp {aka void ()()}' in initialization
CVdmConfig::writeConfig is a void function.
typedef void (*fp)();
fp fpList[] = {&valvesCalib,&CVdmConfig::writeConfig} ;
What do I wrong ?
best regards
Werner
Without seeing the rest of your code, there is not much I can debug, but here is an example that works:
#include <iostream>
using namespace std;
void valvesCalib() {
cout << "inside function\n";
}
class CVdmConfig {
public:
static void writeConfig() {
cout << "inside method\n";
}
};
typedef void (*fp)();
fp fpList[] = {
&valvesCalib,
&CVdmConfig::writeConfig
};
int main()
{
for (auto f: fpList) {
f();
}
return 0;
}
/*
Output:
inside function
inside method
Program finished with exit code 0
*/
The problem was the missing static definition in the member function. But this leads into other problems with variables in the class. So I use a wrapper for this.

how to call member methods inside a wrapper class without repeating the method definition inside the wrapper class?

let's assume i have a wrapper class that embeds a single memeber:
class wrapper {
public:
Object obj;
// the rest ...
};
if the member variable obj has some methods, how can i call the member variable method without explicitly defining methods in the wrapper class like this?
class wrapper{
public:
void foo { obj.foo (); }
int bar (int x) {return obj.bar(x); }
};
i know this is doable in python, but how can i have the same functionality in c++?
ps- please note i don't want to inherit from the member class. this wouldn't't be a wrapper class by definition. i want to achieve this through composition instead.
There are a few ways to handle this. One would be to create a getter to return the wrapper object and another is to override the typecast operator:
class Object {
public:
void foo() {cout << "test" << endl;}
};
class wrapper {
protected:
Object obj;
public:
operator Object&() {return obj;}
Object& getObject() {return obj;}
};
void f(A& a) {
a.foo();
}
int main() {
wrapper w;
((Object)w).foo();
w.getObject().foo();
f(w);
return 0;
}
As you can see, the typecast operator requires you to cast the wrapper object, except when passing as a parameter to the function f().
Also, in your example you already have the obj member as public so it is exposed. You could just:
wrapper w;
w.obj.foo();
Here's a discussion on that: What good are public variables then?

pthread to invoke member func by wrapping it externally

I'm trying to invoke a member function by pthread by using an external wrapper but it doesn't quite work for me, I get a seg fault. Why is this?
Here's a little test program that displays the problem:
#include <iostream>
#include <pthread.h>
class test {
public:
test();
~test();
void RunTh(void);
private:
pthread_t *pid;
};
void *Run_wrp(void *context);
void test::RunTh(void)
{
while(1);
}
test::test()
{
pthread_create(pid,NULL,&Run_wrp,this);
}
test::~test(){}
int main(void) {
test tmp;
std::cin.get();
}
void *Run_wrp(void *context)
{
((test*)context)->RunTh();
}
Your pid member variable is just a pointer, not an actual pthread_t object.
Change it to:
private:
pthread_t pid;
Then create the new thread with:
pthread_create(&pid,NULL,&Run_wrp,this);
Also, if you want to keep everything contained in the class, you can make your Run_wrp() function a static member function of test, as long as you keep the same signature (return value/arguments). It needs to be static, as non-static functions take the this pointer to the class as a hidden argument, and thus end up with a different signature than what you need for pthread_create().

How to use references and pointers in c++ classes?

i have the following problem: I am using an existing class which creates an object called server_t.
Another function expects *server_t as an argument.
I wanted to shrink the code and added a class which has following members:
#ifndef _PMCLASS
#define _PMCLASS
#include "pmlib.h"
class pmServer{
private:
server_t server ;
counter_t counter;
line_t lines;
server_t * server2;
int set, frequency, aggregate ;
public:
pmServer();
pmServer(int set, int frequency, int aggregate);
~pmServer();
void setSet(int s);
void setFrequency(int f);
void setAggregate(int a);
int getSet(void);
int getFrequency(void);
int getAggregate(void);
server_t* getServerT(void);
counter_t* getCounterT(void);
line_t* getLineT(void);
server_t* getZeiger(void);
};
#endif
then i created the constructors:
#include "pmClass.h"
#include <iostream>
using namespace std;
void pmServer::setSet(int s){
this->set = s;
}
void pmServer::setFrequency(int f){
this->frequency = f;
}
void pmServer::setAggregate(int a){
this->aggregate = a;
}
int pmServer::getSet(void){
return set;
}
int pmServer::getFrequency(void){
return frequency;
}
int pmServer::getAggregate(void){
return aggregate;
}
server_t* pmServer::getPointer(){
return &server;
}
pmServer::pmServer(){
set = -1;
frequency = 0;
aggregate = 1;
}
then i tried to create an object ->worked, but then i wanted to use the pm_set_server(...)
it wants following arguments: int pm_set_server( char *ip, int port, server_t *pm_server)
void run() {
build_initial_mesh();
// Construct / read in the initial mesh.
pmServer server1;
pm_set_server("xxx.xxx.xxx.xxx", 6526,server1.getPointer); //its a correct ip address , no panic :)
i got that:
error: argument of type 'server_t*' (pmServer::)() does not match 'server_t*'
but this worked without any problems:
void run() {
// Construct / read in the initial mesh.
//pmServer server1;
server_t test;
pm_set_server("xxx.xxx.xxx.xxx", 6526,&test);
build_initial_mesh();
The thing is, i didn't want to create everytime new ojects and wanted to do that in the constructor...Does somebody have any idea?
thanks.
greetings Thomas
In C++, function calls need brackets*:
pm_set_server("xxx.xxx.xxx.xxx", 6526,server1.getPointer());
*exceptions apply, for operators.

A program using class template, pair, vector

I'm trying to program the following:
A template class map having a pointer to a vector that contains elements std::pair<T,Q>, where T and Q are template types. It's supposed to work similarly to std::map and T is 'key' type, whereas Q stands for 'value' type. Besides the following should be implemented:
1. Constructor & destructor.
2. Function empty returning bool (if the object is empty).
3. Function size (using count_if)
4. Function clear that deletes all vector records.
5. Operator [] which allows for: map["PI_value"] = 3.14; It should use function find
6. Operators =, ==, !=, >> (using equal function)
I've been trying to code the above task, but have stuck on the code below.
Do you have any ideas to repair this mess?
#include <iostream>
#include <tuple>
#include <utility>
#include <algorithm>
#include <vector>
using namespace std;
template <typename T, typename Q>
class mapa
{
private:
vector<std::pair<T,Q>>* ptr;
public:
/**< DEFAULT CONSTRUCTOR/////////////////////////// */
mapa()
{
ptr = new vector<std::pair<T,Q>>;
ptr->push_back(std::pair<T,Q>(0,0));
}
/**< DESTRUCTOR////////////////////////////////////// */
~mapa(){ delete ptr;}
/**< EMPTY()////////////////////////////// */
bool empty()
{
if(ptr)
return false;
else
return true;
}
/**< SIZE()///////////////////////////////// */
int size()
{
return ptr->size();
}
/**< CLEAR()///////////////////////////////// */
void clear()
{
ptr->clear(ptr->begin(), ptr->end());
}
/**< OPERATOR[]/////////////////////////////////////////// */
vector<std::pair<T,Q>>* & operator[](T key)
{
auto ptr2 = ptr;
if(empty())
{
std::pair<T,Q> para;
para.first = key;
para.second = 0;
ptr2->push_back(para);
//ptr2->push_back(std::pair<T,Q>(key,0));
}
else
{
auto ptr2 = find_if( ptr->begin(), ptr->end(),
[](std::pair<T,Q> example,T key)
{
return(example.first==key);
}
);
}
return ptr2;
}
}; //class end
The lambda provided to std::find_if is declared wrong.
If you see e.g. this reference for std::find_if, you will see that the functions should be like
bool pred(const Type &a)
That means the lambda should be something like
[&key](const std:pair<T, Q>& element) { return element.first == key }
There are also other problems with your operator[] function, like that it should return Q& instead of a reference to the vector pointer. You should also remember that std::find_if returns an iterator to the found element, or end() if not found.