Private member functors for a C++ class - c++

I'm writing a class where I would like to have some member methods that have some data associated with them, specifically which mechanical systems of a robot they require use of. I thought I could write them as functors, something like this (this isn't my actual code):
class MyRobot : public Robot {
public:
MyRobot();
void runRobot();
private:
Command do_something_,
do_another_thing_;
}
And then initialize do_something_ with a lambda in the constructor like:
do_something_( [] {
do_first_thing();
do_second_thing();
} );
And then tell do_something_ what requirements it has:
do_something_.requires( system_a );
do_something_.requires( system_b );
And in runRobot() I would tell the robot's scheduler to execute the commands:
void MyRobot::runRobot() {
scheduler.add(do_something_);
scheduler.add(do_another_thing_);
}
But I have come to realize that as the number of commands grows, the less manageable the constructor for MyRobot will become, as every command will have its body defined there. I could make a corresponding private method for each command and initialize them with a function pointer instead of a lambda, but that just seems more convoluted. I could also subclass Command for each specific command and thereby have the body and requirements in a separate file for each one, but that feels like a lot of overhead for a fairly simple task. Is there a good way to do this that I'm not aware of?

You can define the Command class to take a std::function and an initializer list of "requirements" as you have them. Then, instead of using lambdas you can make do_something and do_another_thing their own private member functions so you don't have to define their bodies in the constructor. Finally, in the constructor you can construct the Command instances by binding the private member functions with the this pointer of the current MyRobot instance while also giving them a list of requirements. The Command objects should be able to modify the private state of MyRobot instances. An example is below. Also, see example output.
#include <functional>
#include <iostream>
#include <vector>
enum System { SYS_A, SYS_B, SYS_C };
class Command {
public:
typedef std::function<void()> FuncType;
Command(FuncType func, std::initializer_list<System> requirements)
:func_(func), requirements_(requirements) { }
void operator()() {
std::cout << "Executing Command:" << std::endl;
for ( System s : requirements_ )
std::cout << " REQUIRES " << static_cast<int>(s) << std::endl;
func_();
}
private:
FuncType func_;
std::vector<System> requirements_;
};
class Scheduler {
public:
void add(Command c) {
c();
}
};
class Robot {
public:
Robot()
:do_something_ (std::bind(&Robot::do_something, this), {SYS_A, SYS_B}),
do_another_thing_(std::bind(&Robot::do_another_thing, this), {SYS_A, SYS_C}) { }
void runRobot() {
s_.add(do_something_);
s_.add(do_another_thing_);
}
private:
void do_first_thing() { std::cout << " FIRST THING!" << std::endl; }
void do_second_thing() { std::cout << " SECOND THING!" << std::endl; }
void do_third_thing() { std::cout << " THIRD THING!" << std::endl; }
void do_something() { do_first_thing(); do_second_thing(); }
void do_another_thing() { do_first_thing(); do_third_thing(); }
Command do_something_;
Command do_another_thing_;
Scheduler s_;
};
int main(int, char**) {
Robot().runRobot();
}

Related

How to assign a struct function pointer to a struct function

I have a struct Game with a function pointer called onBegin
struct Game {
// ...
void (*onBegin)(Game&);
// ...
};
What I am attempting to do is allow the user to create their own onBegin function, in which they could say
void CustomFunc(Game& g) {
// Do something
}
Game g = Game();
g.onBegin = *CustomFunc;
What I am attempting to do is make a function and then set the pointer onBegin to point at that default function.
struct Game {
public:
void (*onBegin)(Game&);
private:
void defualtOnBegin(Game&);
};
// In the constructor
Game::Game() {
// ...
this->onBegin = this->defaultOnBegin; // This is what is giving me the error
}
I receive the error: a pointer to a bound function may only be used to call the function and do not know what is wrong here.
What I am attempting to do is allow the user to create their own onBegin function...
You could achieve that in different ways, however as you want to go for a function-pointer approach, you might want to utilize std::function like:
#include <iostream>
#include <functional>
struct Game {
public:
Game(std::function<void(Game&)> customOnBeginFnc = nullptr) {
if(customOnBeginFnc) {
customOnBeginFnc(*this);
} else {
defaultOnBegin(*this);
}
}
private:
void defaultOnBegin(Game&) {
std::cout << "Default 'onBegin'\n";
}
};
void customOnBegin(Game&) {
std::cout << "Custom 'onBegin'\n";
}
int main() {
{
std::cout << "Starting a 'default' game...\n";
Game g;
}
{
std::cout << "Starting a 'customized' game...\n";
Game g(customOnBegin);
}
}
Run it here.
The advantage of that approach would be that you are not limited to free functions but you could also bind a member function to it via a lambda or std::bind.

Any techniques or tricks to modifying existing functions in C++?

Within JavaScript, you can pull off something like this:
function bunny() { alert("The bunny jumped."); }
var oldBunny = bunny;
function bunny() {
oldBunny();
alert("The bunny also ran.");
}
bunny(); // The bunny Jumped. The bunny also ran.
As one can see, the old "bunny" function had code appended to it by copying to a variable, then recreating the function with the same name. The copy of the original function runs, and the new code also runs.
I wish to replicate a similar mechanic in C++.
Now before you have a meltdown and start explaining the differences between static and dynamic languages, I get it. I'm not looking for something identical to what's provided, but I do desire something similar.
Furthermore, I'm not trying to do this to modify existing code; I wish to format my own source code to allow such a mechanic for other users to take advantage of.
One of the first ideas I had was to perhaps setup various macros within the code that could later be modified by other files.
Another idea would be to create a Signal and Slots system like in QT. Though I have no clue how to do such a thing myself.
Thank you for reading; I hope you have some suggestions.
Well, if you recognize which feature of JavaScript functions makes this possible, it's not too hard to do the same in C++. In JavaScript functions also have closures, which regular function in C++ don't have. But C++ lambdas are of a closure type. And if one defines bunny to be something which can both hold an object of a closure type, and be reassigned, you're all set.
The C++ standard library offers a nice default choice for this, in the form of std::function. We can just re-write your original JavaScript as follows:
std::function<void()> bunny = [] {
std::cout << "The bunny jumped.\n";
};
auto oldBunny = std::move(bunny);
bunny = [oldBunny] {
oldBunny();
std::cout << "The bunny also ran.\n";
};
bunny();
You can use functors.
#include <iostream>
#include <string>
class Base
{
public:
virtual std::string operator ()()
{
return "Base call";
}
virtual ~Base() {}
};
class Derived : public Base
{
public:
virtual std::string operator()()
{
return "Wrapper: " + Base::operator()();
}
};
int main()
{
Base* pFun = new Base;
std::cout << "Now check Base: " << (*pFun)() << std::endl;
delete pFun;
pFun = new Derived;
std::cout << "Now check Derived: " << (*pFun)() << std::endl;
return 0;
}
Assuming the goal is to allow the calling code to extend the program's functionality beyond what the initial code provided, I might use a user-updatable array of functor-objects, something like this:
#include <iostream>
#include <memory>
class Function
{
public:
virtual void Call() = 0;
};
typedef std::shared_ptr<Function> FunctionSharedPointer;
class OldBunny : public Function
{
public:
virtual void Call()
{
std::cout << "The bunny jumped." << std::endl;
}
};
class NewBunny : public Function
{
public:
NewBunny(FunctionSharedPointer oldFunction) : _oldFunction(oldFunction) {/* empty */}
virtual void Call()
{
_oldFunction->Call();
std::cout << "The bunny also ran." << std::endl;
}
private:
FunctionSharedPointer _oldFunction;
};
enum {
FUNCTION_BUNNY,
// other functions could be declared here later...
NUM_FUNCTIONS
};
// Our table of functions that the user can Call() if he wants to
static FunctionSharedPointer _functionTable[NUM_FUNCTIONS];
// Wrapper function, just to keep users from accessing our table directly,
// in case we ever want to change it to something else
void CallFunction(int whichFunction)
{
_functionTable[whichFunction]->Call();
}
// Another wrapper function
void SetFunction(int whichFunction, FunctionSharedPointer newFunctionDefinition)
{
_functionTable[whichFunction] = newFunctionDefinition;
}
// And another
FunctionSharedPointer GetFunction(int whichFunction)
{
return _functionTable[whichFunction];
}
int main(int argc, char ** argv)
{
// Our default function values get set here
SetFunction(FUNCTION_BUNNY, std::make_shared<OldBunny>());
std::cout << "before:" << std::endl;
CallFunction(FUNCTION_BUNNY);
// Now let's update an entry in our function table to do something different!
FunctionSharedPointer op = GetFunction(FUNCTION_BUNNY);
FunctionSharedPointer np = std::make_shared<NewBunny>(op);
SetFunction(FUNCTION_BUNNY, np);
std::cout << "after:" << std::endl;
CallFunction(FUNCTION_BUNNY);
return 0;
}
void bunny()
{
cout << "The bunny jumped." << endl;
}
void oldBunny()
{
bunny();
}
void newBunny()
{
bunny();
cout << "The bunny also ran." << endl;
}
#define bunny newBunny
int main()
{
bunny();
return 0;
}
If you don't need oldBunny(), just remove it.

Best practices for dependency injection via constructor

Inversion of control is a value-proof technique which is used to modularize a system and decouple the components from each other.
Low coupling is always an advantage: it simplifies automatic testing of the components and makes the code better conforming to single responsibility principle.
Among the ways to declare a dependency to another class (service locator, property injection calling a public method / setting a public property...), the constructor injection seems the best approach.
Though it's probably the most difficult one (at least from the listed three) to implement, it comes with significant advantages:
all the dependencies are truly visible with constructor signature;
cyclic dependencies don't happen because of the well-defined order of instantiation.
What are the pros / cons of the many choices C++ offers to perform the injection via constructor?
Instance copyable class
class object
{
public:
object(dependency d) : dep_(d) {}
private:
dependency dep_;
};
Only works in case dependency class is completely stateless, i.e. doesn't have any members. Practically, this rarely happens because dependency class may store its own dependency.
Raw pointer
class object
{
public:
object(dependency *d) : dep_(d)
{
if (d == nullptr)
throw std::exception("null dependency");
}
private:
dependency *dep_;
};
This works like true injection. We're required to check the passed pointer for nullptr value.
object class does not own dependency class, thus it's the responsibility of calling code to make sure the object is destroyed before the dependency object.
In real application, it's sometimes very difficult to validate.
Reference
#define DISALLOW_COPY_AND_ASSIGN(Class) \
Class(const Class &) = delete; \
Class &operator=(const Class &) = delete
class object
{
public:
object(dependency &d) : dep_(d) {}
DISALLOW_COPY_AND_ASSIGN(object);
private:
dependency &dep_;
};
The reference cannot be null, so it's a bit safer in this prospective.
However this approach brings additional constraints to object class: it has to be non-copyable since a reference cannot be copied. You have to either manually override assignment operator and copy constructor to stop from copying or inherit it from something like boost::noncopyable.
Like with raw pointer, the ownership constraint is in place. Calling code should provide the correct destruction order for both classes, otherwise the reference becomes invalid and application crashes with access violation.
If the dependency is a const reference:
class object
{
public:
object(const dependency &d) : dep_(d) {}
private:
const dependency &dep_;
};
you should pay attention to the fact that the object class accepts references to temporary objects:
dependency d;
object o1(d); // this is ok, but...
object o2(dependency()); // ... this is BAD.
Further details:
C++: non-temporary const reference
What are the advantages of boost::noncopyable for several approaches to prevent copying a class
Should I prefer pointers or references in member data?
Using reference as class members for dependencies
Smart pointer
class object
{
public:
object(std::shared_ptr<dependency> d) : dep_(d)
{
if (!d)
throw std::exception("null dependency");
}
private:
std::shared_ptr<dependency> dep_;
};
Similar to raw pointer but the ownership is controlled by smart pointer mechanism.
Still need to check for nullptr in the constructor body.
The major advantage is the dependency object lifetime control: there is no need for the calling application to properly control the destruction order (but consider that you need to be very careful when designing your APIs with std::shared_ptr).
Once the dependency class is no longer used it's automatically destroyed by shared_ptr destructor.
There are cases when shared_ptr owned objects are not destroyed (so called cyclic references). However, with constructor injection, cyclic dependencies aren't possible due to the specific well-defined order of construction.
This works of course if no other injection methods are used across the application.
A smart pointer has a small overhead but it isn't a real problem in the majority of cases.
Further details:
Disadvantages of shared_ptr
GotW #91: Smart Pointer Parameters
This is an old question but for me this is a hot topic because I've found automatic dependency injection sorceries in all web the framewrks I could hear of, they are often built with introspection shananigans and I always have great time discovering their implementations. But I couldn't find an easy way to do the same in C++.
The service locator approach can solve the problem pretty well indeed but declaring the dependencies in the constructor and getting rid of such pattern in between seems cleaner and more flexible to use because it is easier to instantiate your classes passing different instances of your services.
But the service locator approach can also handle cyclic dependencies because they can be lazily picked, and sometimes cyclic dependencies can happen (maybe in bad code only).
Unfortunately I haven't figured out way to detect the types of the arguments in constructors and automatically inject instances of such types, yet.
Anyway I want to share the best solution I found so far to automatically inject deendencies in classes. It is similar to a service locator that handles its service as a singleton with smart pointers and can be used for dependency injection, but it have to be revised to allow two classes that have some dependencies in common to get different instances of the same type.
template<typename T>
struct di_explicit
{
static std::shared_ptr<T> ptr;
virtual ~di_explicit()
{
if(di_explicit<T>::ptr.use_count() == 1) {
reset();
}
}
virtual std::shared_ptr<T> get()
{
return di_explicit<T>::ptr;
}
static void reset()
{
di_explicit<T>::ptr.reset();
}
static void swap(std::shared_ptr<T> arg)
{
arg.swap(di_explicit<T>::ptr);
}
static void emplace(auto && ... args)
{
swap(std::make_shared<T>(std::forward(args) ...));
}
static void emplace_if_not_exists(auto && ... args)
{
if(!di_explicit<T>::ptr) {
emplace(std::forward(args) ...);
}
}
};
template<typename T>
std::shared_ptr<T> di_explicit<T>::ptr {};
template<typename T>
struct di : di_explicit<T>
{
di(auto && ... args)
{
di_explicit<T>::emplace_if_not_exists(std::forward(args) ...);
}
};
template<typename T>
struct di_lazy : di_explicit<T>
{
auto get(auto && ... args)
{
di_explicit<T>::emplace_if_not_exists(std::forward(args) ...);
return di_explicit<T>::ptr;
}
};
The ideas behind the above snippet are:
It is a logic wrapper that handles the memory of another class, such wrapper is able to automatically create an instance of the managed class and pass the reference as a singleton when requested, the memory is automatically deallocated when there are no more reference to the managed object.
It is possible to use a specific instance of the managed class (or a subtype) so that the user can declare a dependency to an interface of the needed service and instanciate the concrete dependency when the program is running or a mock during tests.
In case of circular dependency there is a way to lazily instanciate the needed dependency.
The basic logic is coded in the base class di_explicit<T> that uses a static shared_ptr<T> to make the singletons, and a destructor that resets the shared pointer when the last reference left is the static one (stored in di_explicit<T>).
The struct di : di_explicit<T> retrive the dependency in its constructor while di_lazy : di_explicit<T> only does it when the dependency is requested (in the get() method).
The following is an example (non lazy) with a mock.
namespace {
struct dependency {
virtual void do_something() {
std::cout << "doing something" << std::endl;
}
};
struct mock : dependency {
using dependency::do_something;
void do_something() {
std::cout << "mocking something" << std::endl;
}
};
struct srv {
di<dependency> dep;
void do_stuff() {
std::cout << "doing stuff" << std::endl;
return dep.get()->do_something();
}
};
int test = [](){
// the classes are not instanciated yet
std::cout << "ptr exists " << !!di<srv>::ptr << std::endl;
{
// the classes instanciated here
di<srv> s;
s.get()->do_stuff();
std::cout << "ptr exists " << !!di<srv>::ptr << std::endl;
} // <- the instances are destroyed here
std::cout << "ptr exists " << !!di<srv>::ptr << std::endl;
{
// use a mock instance
di_explicit<dependency>::swap(std::make_shared<mock>());
di<srv>{}.get()->do_stuff();
} // <- the mock is destroyed here too
std::cout << "ptr exists " << !!(di<dependency>::ptr) << std::endl;
return 0;
}();
}
The following is an example with circular references and di_lazy.
namespace {
struct dep_2;
struct dep_3;
struct dep_1 {
di_lazy<dep_2> dep;
void do_something();
};
struct dep_2 {
di_lazy<dep_3> dep;
void do_something();
};
struct dep_3 {
di_lazy<dep_1> dep;
void do_something() {
std::cout << "dep_3 do_something" << std::endl;
dep.get()->do_something();
}
virtual void do_something_else() {
std::cout << "dep_3 do_something_else" << std::endl;
}
};
void dep_1::do_something() {
std::cout << "dep_1 do_something" << std::endl;
dep.get()->do_something();
}
void dep_2::do_something() {
std::cout << "dep_2 do_something" << std::endl;
dep.get()->do_something_else();
}
struct srv_2 {
di<dep_3> dep;
void do_something() {
std::cout << "srv_2 do_something" << std::endl;
return dep.get()->do_something();
}
};
int result = [](){
{
// neither the dependencies or the service are requested yet
di_lazy<srv_2> wrapper{};
// here the service is requested
auto s = wrapper.get();
// dependencies are requested inside this function
s->do_something();
}
{
struct mock_dep_3 : dep_3 {
virtual void do_something_else() {
std::cout << "dep_3 do_something_else MOCKED!" << std::endl;
}
};
// a mock can be used with di_lazy as well
di_explicit<dep_3>::swap(std::make_shared<mock_dep_3>());
di<srv_2>{}.get()->do_something();
}
return 0;
}();
}
I know there is room for improvements (any sugestion are appreciated), I hope you find it useful
EDIT
I found a sligly better way to do the same but this time extending the std::shared_ptr class itself.
It is still some kind of service locator but with the following snippet is also possible to pass shared pointers as arguments in your constructors
template<typename T>
class di : public std::shared_ptr<T>
{
static std::shared_ptr<T> ptr;
public:
static void reset()
{
di<T>::ptr.reset();
}
static di<T> replace(std::shared_ptr<T> ptr)
{
di<T>::ptr = ptr;
return di<T>::ptr;
}
template<typename ... args_t>
static di<T> emplace(args_t && ... args)
{
return di<T>::replace(std::make_shared<T>(
std::forward<args_t>(args) ...
));
}
static di<T> instance()
{
return di<T>::ptr;
}
~di()
{
if(this->is_linked() && di<T>::ptr.use_count() <= 2){
di<T>::ptr.reset();
}
}
bool is_linked()
{
return *this && di<T>::ptr.get() == this->get();
}
template<typename ... args_t>
di(args_t && ... ptr) : std::shared_ptr<T>(std::forward<args_t>(ptr) ...)
{}
};
template<typename T>
std::shared_ptr<T> di<T>::ptr {};
With this class you can pass the instance of some service to another using constructor
ie
struct logger_interface
{
virtual void log(std::string) = 0;
virtual ~logger_interface() = default;
};
struct some_service_interface
{
virtual void serve() = 0;
virtual ~some_service_interface() = default;
};
struct logger_with_id : logger_interface
{
static int counter;
int id = ++counter;
void log(std::string s) {
std::cout << id << ") " << s << std::endl;
}
};
int logger_with_id::counter = 0;
struct some_service : some_service_interface
{
di<logger_interface> logger;
some_service(
di<logger_interface> logger = di<logger_interface>::instance()
) :
logger(logger)
{}
void serve() {
logger->log("serving...");
}
};
int app = []() {
di<logger_interface>::replace(di<logger_with_id>::emplace());
di<some_service_interface>::replace(di<some_service>::emplace());
std::cout << "running app"<< std::endl;
di<logger_interface>::instance()->log("app");
di<some_service_interface>::instance()->serve();
std::cout << std::endl;
return 0;
}();
Will print
running app
1) app
1) serving...
And if you need you can override the dependency for some service
struct decorated_logger : logger_interface {
di<logger_interface> logger;
decorated_logger(
di<logger_interface> logger = di<logger_interface>::instance()
) :
logger(logger)
{}
void log(std::string s) {
logger->log("decorating...");
logger->log(s);
}
};
int app_with_custom_logger_on_service = [](
di<logger_interface> logger,
di<some_service_interface> service
) {
std::cout << "running app_with_custom_logger_on_service"<< std::endl;
logger->log("app");
service->serve();
std::cout << std::endl;
return 0;
}(
di<logger_interface>::replace(std::make_shared<logger_with_id>()),
di<some_service_interface>::replace(std::make_shared<some_service>(
std::make_shared<decorated_logger>(std::make_shared<logger_with_id>())
))
);
Will print
running app_with_custom_logger_on_service
2) app
3) decorating...
3) serving...
This can also be used for tests
struct mock_logger : logger_interface {
void log(std::string) {
std::cout << "mock_logger" << std::endl;
}
};
struct mock_some_service : some_service_interface {
void serve() {
std::cout << "mock_some_service" << std::endl;
}
};
int test = [](
di<logger_interface> logger,
di<some_service_interface> service
) {
std::cout << "running test"<< std::endl;
logger->log("app");
service->serve();
std::cout << std::endl;
return 0;
}(
di<logger_interface>::replace(std::make_shared<mock_logger>()),
di<some_service_interface>::replace(std::make_shared<mock_some_service>())
);
Will print
running test
mock_logger
mock_some_service
I made a gist for this example, you can run it on wandbox with clang

Making all class methods call the same function

So, I've got this situation:
#include "ActionLog.h"
class Library{
ActionLog aLog;
// ... the rest of it is private, mind you :D
public:
Library(...);
void addBook(...);
void removeBook(...);
// ... aaand there's a whole bunch of these :)
};
Now, class ActionLog has a public method void log(...);. It should, once implemented, record the beginning of any activity listed as a method of class Library (and eventually it's success/failure, which is optional).
I'm wondering this: Is there some more elegant way of making every class Library's method call the aLog.log(...); method when/before it starts executing? By "elegant" I mean other than just calling it explicitly in every single method...
I am aware of the Python version of the solution for the similar problem, but I'm not familiar with Python, so I'm not even sure that the same class-related principles apply.
C++ doesn't have any means of reflection built-in. There's no way to list methods neither in runtime, nor in compile-time. The best you can do is to hide logging into some #define that you will use to define every method, but preprocessor usage is an antipattern in modern C++.
Stick to the current approach.
As polkovnikov.ph said, without reflection you wouldn't be able to use the python's approach to this.
Just for fun I am going to leave this here but I wouldn't recommend its use:
#include <iostream>
class Logger
{
public:
void log(std::string entry)
{
std::cout << entry << std::endl;
}
};
class A
{
Logger mylog;
public:
void foo()
{
std::cout << "Doing foo" << std::endl;
}
Logger& getLogger()
{
return mylog;
}
};
#define CALL_FUNC_AND_LOG(obj,func) \
{ obj.getLogger().log("Logging "#func); obj.func(); }
int main()
{
A a;
CALL_FUNC_AND_LOG(a,foo);
return 0;
}
http://ideone.com/q0VHj6
Or another version that automatically logs the end of scope of the method.
#include <iostream>
class Logger
{
std::string _entry;
public:
Logger(std::string entry)
{
_entry = entry;
std::cout << "Starting execution of " << entry << std::endl;
}
~Logger()
{
std::cout << "Ending execution of " << _entry << std::endl;
}
};
class A
{
public:
void foo()
{
std::cout << "Doing foo" << std::endl;
}
};
#define CALL_FUNC_AND_LOG(obj,func) \
{ \
Logger _mylogger(""#func); \
obj.func(); \
\
}
int main()
{
A a;
CALL_FUNC_AND_LOG(a,foo);
return 0;
}
http://ideone.com/DHf3xu

C++ function with function parameter more elegant

I have the following code:
#include <iostream>
using namespace std;
class A
{
int m_value;
public:
A(int value)
{
m_value = value;
funcA(&A::param);
}
void funcA(void (A::*function)(int))
{
(this->*function)(m_value);
}
void param(int i)
{
cout << "i = " << i << endl;
}
};
int main()
{
A ob(10);
return 0;
}
I have a class in which I call a function that receives another function as parameter. The function call is at line funcA(&A::param). What I want is to be able to pass a function as parameter without being necessary to specify the class scope: funcA(&param). Also I didn't want to use typedefs that's why I have the code a little 'dirty'.
Is there any possibility to achieve this?
This cannot be done. A function pointer in a class must be identified using the class scope (A::function)
That is kind of ugly.
The first thing you should look at doing is recoding things to use inheritence and dynamic dispatch instead. To do this you change the A class to have a virtual method that funcA calls
class A {
...
void funcA () {
custom_function(m_value);
}
protected:
virtual void custom_function (int)=0;
}
Now for every different custom_function you want to use, you declare a new class derived from A, and implement the function in there. It will automagically get called from funcA:
class A_print : public A {
public:
virtual void custom_function (int param) {
std::cout << "param was " << param << std::endl;
}
}
If that isn't flexible enough for you, the next best C++-ish solution would be to implement a functor (an object that acts as a function, possibly even overriding the ()operator.
I don't understand why you can't just do this:
#include <iostream>
using namespace std;
class A
{
int m_value;
public:
A(int value)
{
param(value);
}
void param(int i)
{
cout << "i = " << i << endl;
}
};
int main()
{
A ob(10);
return 0;
}