Use member function as function pointer - c++

I've never used function pointers before and I'm having some trouble getting my code to work. This is what I have
TestClass.h:
class TestClass
{
public:
void function1();
void function2();
void function3(void (*funcPtr)(void))
void function4();
};
TestClass.cpp
void TestClass::function1()
{
//CODE
}
void TestClass::function2()
{
//CODE
}
void TestClass::function3(void (*funcPtr)(void))
{
//CODE
funcPtr();
//CODE
}
void TestClass::function4()
{
function3(function1);
function3(function2);
}
This give me the error
"nonstandard form for taking the address of a member function
I tried to add TestClass:: infront of the *funcPtr but that gives me even more errors

With member function pointer, it should be something like:
void TestClass::function3(void (TestClass::*funcPtr)())
{
//CODE
(this->*funcPtr)();
//CODE
}
void TestClass::function4();
{
function3(&TestClass::function1);
function3(&TestClass::function2);
}
With function pointer
class TestClass
{
public:
static void function1(); // static added
static void function2(); // static added
void function3(void (*funcPtr)(void))
void function4();
};
void TestClass::function3(void (*funcPtr)())
{
//CODE
funcPtr();
//CODE
}
void TestClass::function4();
{
function3(&TestClass::function1);
function3(&TestClass::function2);
}

I suggest you to use std::bind and std::function, which provide a better readability and more checking for you
http://en.cppreference.com/w/cpp/utility/functional/bind
#include <functional>
void TestClass::function3( std::function<void (void)> funcPtr )
{
//CODE
funcPtr();
//CODE
}
void TestClass::function4()
{
function3( std::bind(&TestClass::function1, this) );
function3( std::bind(&TestClass::function2, this) );
}

Related

Storing functions from class in array and invoke them c++

i try store a functions(methods) from class in array and use them.
The error handle is
In function 'int main()':| 'actions' was not declared in this
scope
this my code(i delete unnecessary code)
the class.h:
class Calculator
{
public:
int num1,num2;
void (Calculator::*actions[4])();
void add();
void minuz();
void multi();
void div();
Calculator();
};
class.cpp:
void Calculator::add()
{}
void Calculator::minuz()
{}
void Calculator::div()
{ }
void Calculator::multi()
{}
Calculator::Calculator()
{
actions[0]=add;
actions[1]=minuz;
actions[2]=div;
actions[3]=multi;
}
main:
Calculator cal;
.....
.....
cal.*actions[num]();
C++ syntax for function pointer declaration is quite complicated, so it better use typedefs
To call function by pointer you need extra () around dereferenced function pointer.
Finally it will be:
class Calculator
{
public:
typedef void (Calculator::*action)();
int num1,num2;
action actions[4];
void add();
void minuz();
void multi();
void div();
Calculator();
};
void Calculator::add()
{}
void Calculator::minuz()
{}
void Calculator::div()
{ }
void Calculator::multi()
{}
Calculator::Calculator()
{
actions[0]=&Calculator::add;
actions[1]=&Calculator::minuz;
actions[2]=&Calculator::div;
actions[3]=&Calculator::multi;
}
int main(int, char**) {
Calculator cal;
int num = 0;
(cal.*cal.actions[num])();
return 0;
}
for better readability I'd suggest add function Calculator::call_by_index(int):
void Calculator::call_by_index(int index)
{
(this->*actions[index])();
}
and call it in such way:
cal.call_by_index(num);
Using a typedef usually helps: (c++03)
Live On Coliru
class Calculator
{
public:
int num1,num2;
typedef void (Calculator::*Action)();
Action actions[4];
Calculator() {
actions[0]=&Calculator::add;
actions[1]=&Calculator::minuz;
actions[2]=&Calculator::div;
actions[3]=&Calculator::multi;
}
private:
void add() {}
void minuz() {}
void multi() {}
void div() {}
};
int main() {
Calculator cal;
(cal.*cal.actions[1])();
}
C++11 aliases
C++11 makes it easier:
using Action = void (Calculator::*)();
Action actions[4];
See also https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types
Live On Coliru
std::function<>
Also in c++11 (or boost if you want it in c++03):
using Action = std::function<void(Calculator&)>;
Action actions[4];
Which you would still call like
cal.actions[1](cal);
I'd pre-bind to the Calculator instance:
Live On Coliru
#include <functional>
class Calculator
{
public:
int num1,num2;
using Action = std::function<void()>;
Action actions[4];
Calculator() {
actions[0] = [this]() { add(); };
actions[1] = [this]() { minuz(); };
actions[2] = [this]() { multi(); };
actions[3] = [this]() { div(); };
}
private:
void add() {}
void minuz() {}
void multi() {}
void div() {}
};
int main() {
Calculator cal;
cal.actions[1]();
}
You're not calling it right. Since actions is a member of Calculator, you need to reference a Calculator object to get at it.
(cal.*(cal.actions[num]))();
The first cal is the object you're wanting to call the action with, and the second cal is used to access the action you want to call.

variadic templates with template function names for c++11

following this question , I am trying to avoid copy-pasting some code related to calling all of the same-named methods of the mixins of the class BaseSensor.
in sensor.hpp
struct EdgeSensor //a mixin
{
void update(){}
void printStats() {}
};
struct TrendSensor //another mixin
{
void update(){}
void printStats() {}
};
template<typename ... SensorType>
class BaseSensor : public SensorType ... //to my BaseSensor class
{
void update() /*{ what goes in here??? }*/
void printStats() /*{ what goes in here??? }*/
};
in sensor.t.hpp
template<typename ... SensorType>
void BaseSensor<SensorType...>::update()
{
int arr[] = { (SensorType::update(), 0)..., 0 };
(void)arr;
}
template<typename ... SensorType>
void BaseSensor<SensorType...>::printStats()
{
int arr[] = { (SensorType::printStats(), 0)..., 0 };
(void)arr;
}
in main.cpp
int main(int , const char **)
{
{
BaseSensor<EdgeSensor,TrendSensor> ets;
ets.update();
ets.printStats();
}
{
BaseSensor<EdgeSensor> ets;
ets.update();
ets.printStats();
}
}
The above code executes the update() of all the mixins in turn, before going on to execute all the printStats() from all the mixins as well.
I wonder if it is somehow possible to avoid duplicating the implementation of BaseSensor::update() and BaseSensor::printStats() and create a generic (template) function that accepts the name of the target function to execute across all the mixins:
For example, I could create a method runAll()
template<typename ... SensorType>
class BaseSensor : public SensorType ... //to my BaseSensor class
{
void update() /*{ what goes in here??? }*/
void printStats() /*{ what goes in here??? }*/
template<typename FnName>
void runAll(FnName f)
{
int arr[] = { (SensorType::f(), 0)..., 0 };
(void)arr;
}
};
How would I call it then from BaseSensor::update() and BaseSensor::printStats(). I have attempted to use
void update() { runAll<update>(); }
void printStats() { runAll<printStats>(); }
but this does not work (did not expect it to). The problem with passing function name as a function argument (which I see is many other questions such as here is that I do not know how to point to various ::update() functions from BaseSensor::update(). for example
void update() { runAll<update>( update() ); }
is also not correct.
Is it possible to avoid copying in this case? Can this be done in a one-liner so as to avoid alot of copying using c++11 (i.e. without using generic lambdas as is done here)? How would the template parameters look like if I where to move a working runAll() into file "sensor.t.hpp" ?
Thank you.
As long as the functions to be called are two, you can use a dedicated structure and rely on overloading to solve it.
It follows a minimal, working example:
#include<iostream>
struct Executor {
template<typename T>
static void execute(int, T &t) {
t.update();
}
template<typename T>
static void execute(char, T &t) {
t.printStats();
}
};
struct EdgeSensor
{
void update() { std::cout << "EdgeSensor::update" << std::endl; }
void printStats() { std::cout << "EdgeSensor::printStats" << std::endl; }
};
struct TrendSensor
{
void update() { std::cout << "TrendSensor::update" << std::endl; }
void printStats() { std::cout << "TrendSensor::printStats" << std::endl; }
};
template<typename ... SensorType>
class BaseSensor : public SensorType ...
{
template<typename T>
void execute() {
int arr[] = { (Executor::execute(T{}, static_cast<SensorType&>(*this)), 0)..., 0 };
(void)arr;
}
public:
void update() {
execute<int>();
}
void printStats() {
execute<char>();
}
};
int main() {
BaseSensor<EdgeSensor,TrendSensor> ets;
ets.update();
ets.printStats();
}
In case you have more than two functions to be called, I guess the choice trick applies well here.
You can still write the (simplified version of) generic lambda manually:
void update() {
execute([](auto &t) { t.update(); });
}
becomes so
void update() {
struct {
template <typename T>
void operator () (T& t) const { t.update(); }
} updater;
execute(updater);
}

assigning member function to be other function

Can a function be assigned or alter its definition, just like overriding a function by derived classes.
But at this time, it is out of scope from the class.
I mean like this:
//class.h
class MClass
{
public:
void function(); // this is the function I am referring to.
}
//class.cpp
void MClass::function() { }
//file1.cpp
MClass mclass;
void globalFunction() { }
mclass.function = globalFunction; //is this even possible?
Your function() is a real function, you want function Callback instead.
see sample program: on ideone
#include <functional>
class MClass
{
public:
std::function<void(void)> func_ptr;
void setFuncPtr(const std::function<void(void)>& ptr)
{
func_ptr = ptr;
}
void callFuncPtr()
{
func_ptr();
}
};
You could set func_ptr to any callabe objet
MClass m;
m.setFuncPtr(globalFunction); // set to standalone function
m.callFuncPtr();
// set lambda to it
m.setFuncPtr([](){ std::cout << " do something " << std::endl; });
m.callFuncPtr();
Or bind to other object
struct Test
{
void print() { std::cout << "Test::print" << std::endl; }
};
Test t;
m.setFuncPtr(std::bind(&Test::print, t));
m.callFuncPtr();
You could also pass parameter to function by using std::bind and placeholders.
There are two ways :
c++03 - you can use function pointer :
class MClass
{
public:
void (*function)();
};
void globalFunction()
{
// ...
}
MClass obj;
mclass.function = globalFunction;
in c++11 you can use functors :
class MClass
{
public:
std::function<void()> function;
};
void globalFunction()
{
// ...
}
MClass obj;
mclass.function = globalFunction;

Passing Void into a class as a pointer then executing its contents

How can I pass a function as an argument and then execute it. I'm trying to do something like this:
class Foo{
private:
void (*external);
public:
Foo(void (*function)()){ *external = *function; }
~Foo(){ }
bool Execute(){
*external(); // Somehow execute 'external' which does the same thing with 'function'
return true
}
};
void pFnc(){
printf("test");
}
int main(){
Foo foo = Foo(&pFnc);
foo.Execute();
return 0;
}
This is not working of course.
You were close.
class Foo
{
public:
typedef void(*FN)(void);
Foo(FN fn) : fn_(fn) {};
bool Execute()
{
fn_();
return true;
}
FN fn_;
};
void pFunc(){
printf("test");
}
int main()
{
Foo foo(&pFunc);
foo.Execute();
}
Try:
void (*external)();
Your original declaration is a pointer to void, not a pointer to a function returning void.
Set it with
external = function;
and execute with
external();
Also, external has to be declared as a function pointer void (*external)(). Otherwise, you have to cast between function- and void-pointer.

How to declare a function identifier

If i have a sample code like this:
void func_1 {
.......
func_2;
}
func_2{
.......
}
I need to declare a function identifier for func_2 so that the code could run how do i do that?
If func_2 won't call func_1, then you can just reorder them:
void func_2()
{
}
void func_1()
{
// ...
func_2();
}
If they both call each other, then you can declare like so:
void func2();
void func1()
{
// ...
func2();
}
void func2()
{
// ...
func1();
}
void func_2 ();
void func_1 ()
{
...
}
void func_2 ()
{
...
}