#include "stdafx.h"
#include <iostream>
#include <functional>
using namespace std;
class Point
{
public:
Point(double _x, double _y) :x(_x), y(_y) {};
double x;
double y;
};
typedef std::function<void*(void*)> genericFunc;
void * func1(void * argv) {
double * d = (double *)argv;
double x = d[0];
double y = d[1];
Point p(x, y);
Point* pp = &p;
return (void *)pp;
}
void * func2(void * argv) {
double * d = (double *)argv;
double x = d[0];
double y = d[1];
double z = d[2];
double R = x * y * z;
return (void *)&R;
}
void * TestFunc(genericFunc f, void* p)
{
return f(p);
}
int main()
{
double argv[]{ 1.2, 2.3, 3.4 };
Point p = * ( (Point*) TestFunc(&func1, (void*)argv) );
double d = *((double*)TestFunc(&func2, (void*)argv));
cout << "p:" << p.x << "," << p.y << ", d:" << d << endl;
getchar();
return 0;
}
20 November 2018
C++ generic function pointer example / use (void*) as object pointer
C++ pass member function pointer as function parameter example
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <functional>
#include <vector>
#include <string>
using namespace std;
typedef std::function<double(int, int)> funcIntToDouble;
class parent;
class child
{
public:
double childValue;
child()
{
childValue = 10.5;
}
double InChildFunc(funcIntToDouble f, int x, int i)
{
double d = f(x, i) + childValue;
cout << endl << "InChildFunc: " << d << endl;
return d;
}
};
class parent
{
public:
int y;
child childObject;
vector<double> vec{ 1.1, 2.2, 3.3 };
parent()
{
y = 10.0;
}
double ParentFunc(int x, int i)
{
double d = (double)x * y + vec[i];
return d;
}
void CallChildObject(int parentX, int parentI)
{
funcIntToDouble f = [&](int x, int i) {
double d = ParentFunc(x, i);
return d;
};
double r = childObject.InChildFunc(f, parentX, parentI);
cout << endl << "CallChildObject: " << r << endl;
}
};
int main()
{
parent p;
p.CallChildObject(10, 1);
getchar();
return 0;
}
17 November 2018
C++ passing vector as shared_ptr example
#include <functional>
using namespace std;
void Test(shared_ptr<vector<int>> v)
{
vector<int> & r_v = *(v.get());
cout << r_v[1];
}
int main()
{
shared_ptr<vector<int>> a = make_shared<vector<int>>(std::vector<int>{ 1, 2, 3 });
Test(a);
getchar();
return 0;
}
Function Pointer Object example in C++
using namespace std;
typedef std::function<double(int)> funcIntToDouble;
void Test(funcIntToDouble f, int x)
{
double b = f(x);
cout << b;
}
int main()
{
cout << "function object example" << endl;
int a = 10;
funcIntToDouble f = [&](int x) {
double r = (double)(x + a) / 10; //able use use variable a from the calling function
return r;
};
Test(f, 15); //pass the function pointer along with value from variables in scope
getchar();
return 0;
}
Subscribe to:
Posts (Atom)