sorry for the title, it's quite confusing to explain, but it will be more clear with example
In C, I used to write program like this :
void createClassA()
{
}
void createClassB()
{
}
typedef struct {
const char *name;
void (*create_class)();
} MapList;
MapList mapList[] = {
{"A", &createClassA},
{"B", &createClassB },
};
void create(const char *name)
{
int i=0;
for (i=0; i < sizeof(mapList) / sizeof(MapList); i++) {
if (strcmp(name, mapList[i].name) == 0) mapList[i].create_class();
}
}
int main(int argc, char** argv)
{
if (argc < 1) return -1;
create(argv[1]);
return 0;
}
So if I have more types, all I have to do is to create the function itself and add it to the mapList.
but in C++, the best I can do is something like:
#include <iostream>
class myA{};
class myB{};
class myC{};
class Base
{
public:
template<class T>
void createClass()
{
T* t = new T();
//t->doSomethingUseful();
}
void create(const std::string name)
{
if (name=="A") createClass<myA>();
else if (name=="B") createClass<myB>();
else if (name=="C") createClass<myC>();
}
};
int main(int agrc, char** argv)
{
if (argc<1) return -1;
Base b;
b.create(argv[0]);
return 0;
}
Can I create something like :
typedef struct {
std::string name;
[CLASS_TYPE] class_type; <== I don't know how
} MapList;
so I can create a mapping List but fill it with class Type, something like
mapList[] = {
{"A", myA},
{"B", myB},
{"B", myC},
};
and then I can create iteration like:
for (int i=0; i<sizeof(mapList) / sizeof(MapList); i++) {
if (mapList[i].name == name) b.createClass<mapList[i].classType>();
}
Thanks guys :)
In C++ you can use std::function in the <functional> standard header. Specifically, your example for the map list can be written as (with lambdas):
std::map<std::string, std::function<void()>> mapList;
mapList["A"] = []() { /* ... */ };
mapList["B"] = []() { /* ... */ };
or just (without lambdas):
void createClassA() {}
void createClassB() {}
std::map<std::string, std::function<void()>> mapList;
mapList["A"] = createClassA;
mapList["B"] = createClassB;
In C++ you could do that with virtual functions:
struct ClassMaker {
virtual void create_class() = 0;
};
struct ClassMakerA : public ClassMaker {
virtual void create_class() {
...
}
};
struct ClassMakerB : public ClassMaker {
virtual void create_class() {
...
}
};
Now you can create a std::map<std::string,ClassMaker*> with your "factories", like this:
ClassMakerA makerA;
ClassMakerB makerB;
// This syntax requires C++11
std::map<std::string,ClassMaker*> makers = {
{"A", &makerA}
, {"B", &makerB}
};
Finally, you can now call create_class() based on a std::string value, like this:
void create(const std::string &name) {
ClassMaker *maker = makers[name];
if (maker) maker -> create_class();
}
You could look for Boost::any, which provides "a variant value type".
You can use derived classes and object factory, something like that would work. You can improve it by make create method to return smart pointers and make A and B constructors private to avoid creating objects on the stack.
class Base
{
static Base* create(const char *name);
};
class A : public Base
{
};
class B : public Base
{
};
Base* Base::create(const char *name)
{
if(strcmp(name,"A")==0)
return new A();
if(strcmp(name,"B")==0)
return new B();
return 0;
}
int main(int agrc, char** argv)
{
if (argc<1) return -1;
Base *b = Base::create(argv[0]);
return 0;
}
It is somewhat similar to solution by #dasblinkenlight, but avoid virtual functions overhead.
Related
i dont what to manage or less as i can manage raw pointers note in the example i have to delete the object before removeing it from the vector i want to avoid it it here and later
what will be good case to convert this code to using unique_ptr or shared_ptr
class GameState
{
public:
virtual bool onEnter() = 0;
virtual bool onExit() = 0;
virtual std::string getStateID() const = 0;
};
class MenuState : GameState
{
public:
MenuState(){};
virtual ~MenuState(){};
bool onEnter(){};
bool onExit(){};
std::string getStateID() const;
private:
static const std::string s_menuId;
};
class StateMechine
{
public:
void pushState(GameState* pState)
{
m_gameStates.pop_back(pState);
m_gameStates.back()->onEnter();
}
void changeState(GameState* pState)
{
if(!m_gameStates.empty())
{
if(m_gameStates.back()->onExit())
{
delete m_gameStates.back();
m_gameStates.pop_back();
}
}
}
private:
std::vector<GameState*> m_gameStates;
}
int main(int argc ,char** argv)
{
GameState *gs = new MenuState();
StateMechine sm;
sm.pushState(gs);
sm.changeState(gs);
}
The std::vector<GameState*> can be replaced with a std::vector<std::unique_ptr<GameState>>. That way a call to m_gameStates.pop_back() will delete the corresponding object.
class StateMechine
{
public:
void pushState(std::unique_ptr<GameState> pState)
{
m_gameStates.push_back(std::move(pState));
m_gameStates.back()->onEnter();
}
void changeState()
{
if(!m_gameStates.empty())
{
if(m_gameStates.back()->onExit())
{
m_gameStates.pop_back();
}
}
}
private:
std::vector<std::unique_ptr<GameState>> m_gameStates;
};
int main(int argc ,char** argv)
{
StateMechine sm;
sm.pushState(std::make_unique<MenuState>());
sm.changeState();
}
I hope to store the data in three different ways:
1.store to a std::string
2.write to file descriptor
3.both of the above
And I hope to use a uniform interface for these three different methods.
I wrote a simple code sippet to achieve the said goals. The first & second are easy indeed, but for the third I am stuck.
Please pay attention to the comment in the code snippet below, which is what the compiler complains if STORE_BY_FD_AND_STRING is defined.
Here is the code snippet:
#include <memory>
#include <iostream>
#include <unistd.h>
class DataStorage {
public:
DataStorage(int total_count):total_count_(total_count){};
virtual int Store(const char *buffer, int count) = 0;
virtual ~DataStorage(){};
protected:
int total_count_;
};
class DataStorageByStr : public DataStorage {
public:
DataStorageByStr(std::string &str) : str_(str), DataStorage(0){};
int Store(const char *buffer, int count)
{
str_ += std::string(buffer, count);
total_count_ += count;
return 0;
};
protected:
std::string &str_;
};
class DataStorageByFd : public DataStorage {
public:
DataStorageByFd(int &fd):fd_(fd), DataStorage(0){};
int Store(const char *buffer, int count)
{
int ret = write(fd_, buffer, count);
if(ret > 0)
{
total_count_ += ret;
}
return ret;
};
protected:
int &fd_;
};
class DataStorageByStrAndFd : public DataStorageByStr, public DataStorageByFd {
public:
DataStorageByStrAndFd(std::string &str, int &fd):DataStorageByStr(str), DataStorageByFd(fd) {}
int Store(const char *buffer, int count)
{
int ret1 = DataStorageByStr::Store(buffer, count);
int ret2 = DataStorageByFd::Store(buffer, count);
return ((0==ret1) && (0==ret2))?0:-1;
}
};
int StoreSomeData(DataStorage *pstorage, const std::string data_to_store)
{
return pstorage->Store(data_to_store.data(), data_to_store.length());
}
int main()
{
{
std::string str{"storing the string to std::string works !"};
std::string data;
DataStorage *pstorage = new DataStorageByStr(data);
StoreSomeData(pstorage, str);
std::cout << data << std::endl;
}
{
std::string str{"storing the string to fd works !"};
int fd = 1;
DataStorage *pstorage = new DataStorageByFd(fd);
StoreSomeData(pstorage, str);
}
#ifdef STORE_BY_FD_AND_STRING
{
std::string str{"thanks for your attention for this matter!"};
std::string data;
int fd = 1;
DataStorage *pstorage = new DataStorageByStrAndFd(str, fd); //The compiler complain that 'DataStorage' is an ambiguous base of 'DataStorageByStrAndFd'
StoreSomeData(pstorage, str);
}
#endif
}
Any sugestion to achieve all the aforementioned goals?
Thanks to #Sam Varshavchik #Adrian Mole. This code snippet works.
#include <memory>
#include <iostream>
#include <unistd.h>
class DataStorage {
public:
DataStorage(int total_count):total_count_(total_count){};
virtual int Store(const char *buffer, int count) = 0;
virtual ~DataStorage(){};
protected:
int total_count_;
};
class DataStorageByStr : virtual public DataStorage {
public:
DataStorageByStr(std::string &str) : str_(str), DataStorage(0){};
int Store(const char *buffer, int count)
{
str_ += std::string(buffer, count);
total_count_ += count;
return 0;
};
protected:
std::string &str_;
};
class DataStorageByFd :virtual public DataStorage {
public:
DataStorageByFd(int &fd):fd_(fd), DataStorage(0){};
int Store(const char *buffer, int count)
{
int ret = write(fd_, buffer, count);
if(ret > 0)
{
total_count_ += ret;
}
return ret;
};
protected:
int &fd_;
};
class DataStorageByStrAndFd : public DataStorageByStr, public DataStorageByFd {
public:
DataStorageByStrAndFd(std::string &str, int &fd):DataStorageByStr(str), DataStorageByFd(fd), DataStorage(0)
{
}
int Store(const char *buffer, int count)
{
int ret1 = DataStorageByStr::Store(buffer, count);
int ret2 = DataStorageByFd::Store(buffer, count);
return ((0==ret1) && (0==ret2))?0:-1;
}
};
int StoreSomeData(DataStorage *pstorage, const std::string data_to_store)
{
return pstorage->Store(data_to_store.data(), data_to_store.length());
}
int main()
{
{
std::string str{"storing the string to std::string works !"};
std::string data;
DataStorage *pstorage = new DataStorageByStr(data);
StoreSomeData(pstorage, str);
std::cout << data << std::endl;
}
{
std::string str{"storing the string to fd works !"};
int fd = 1;
DataStorage *pstorage = new DataStorageByFd(fd);
StoreSomeData(pstorage, str);
}
#ifndef STORE_BY_FD_AND_STRING
{
std::string str{"thanks for your attention for this matter!"};
std::string data;
int fd = 1;
DataStorage *pstorage = new DataStorageByStrAndFd(str, fd); //The compiler complain that 'DataStorage' is an ambiguous base of 'DataStorageByStrAndFd'
StoreSomeData(pstorage, str);
}
#endif
}
Explanation:
Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes. Without virtual inheritance, if two classes B and C inherit from a class A, and a class D inherits from both B and C, then D will contain two copies of A's member variables: one via B, and one via C. These will be accessible independently, using scope resolution.
Instead, if classes B and C inherit virtually from class A, then objects of class D will contain only one set of the member variables from class A.
This feature is most useful for multiple inheritance, as it makes the virtual base a common subobject for the deriving class and all classes that are derived from it. This can be used to avoid the diamond problem by clarifying ambiguity over which ancestor class to use, as from the perspective of the deriving class (D in the example above) the virtual base (A) acts as though it were the direct base class of D, not a class derived indirectly through a base (B or C).
Let's suppose I have some C++ abstract class and all its inherited classes have different constructors:
class Abstract{
//don't worry, there is some pure virtual method here
}
class A : public Abstract {
public:
A (int Afirst, std::string Asecond, int Athird) {...}
...
}
class B : public Abstract {
public
B (double Bfirst, std::int Bsecond) {...}
...
}
class C : public Abstract {
public
C (std::string Cfirst, double Csecond, int Cthird, float Cfourth) {...}
}
As you can see, all the inherited class have (possibly) different constructors.
Now, I want to write a generic main(), something like:
int main (int argc, char *argv[]){
if(argc < 2){
std::cerr<<"Too few arguments!"<<std::endl;
exit(1);
}
std::string type = argv[1];
Abstract *abs;
if(!type.compare("A"){
if(argc < 5){
std::cerr<<"Too few arguments for A!"<<std::endl;
exit(1);
}
abs = new A(atoi(argv[2]), argv[3], argv[4]);
}
//similar for B, C, D
}
I wonder if there is a best way to do this, for example passing directly char *argv[] to each constructor and make all the checks inside the constructor (and eventually throwing an exception as described here).
You may do something like that to be generic:
// functions to convert const char* to given type
template <typename T> T To(const char*);
template <> int To(const char* s) { return atoi(s); }
template <> const char* To(const char* s) { return s; }
template <> std::string To(const char* s) { return s; }
// ...
// Your classes:
struct Abstract { virtual ~Abstract() = default; };
struct A : Abstract { A (int, std::string, int) {}};
struct B : Abstract { B (int, int) {}};
// ...
namespace detail
{
// Helper functions for the factory.
template <typename T, typename Tuple, std::size_t... Is>
std::unique_ptr<Abstract> make_abstract(const char*argv[], std::index_sequence<Is...>)
{
return std::make_unique<T>(To<std::tuple_element_t<Is, Tuple>>(argv[2 + Is])...);
}
template <typename T, typename Tuple>
std::unique_ptr<Abstract> make_abstract(int argc, const char*argv[])
{
constexpr int tuple_size = std::tuple_size<Tuple>::value;
if (argc < tuple_size) {
throw std::runtime_error("Too few arguments");
}
return make_abstract<T, Tuple>(argv, std::make_index_sequence<tuple_size>());
}
}
// The public factory
std::unique_ptr<Abstract> make_abstract(int argc, const char*argv[])
{
if (argc == 1) {
return nullptr;
}
const std::string name = argv[1];
if (name == "A") {
return detail::make_abstract<A, std::tuple<int, std::string, int>>(argc, argv);
} else if (name == "B") {
return detail::make_abstract<B, std::tuple<int, int>>(argc, argv);
}
// ...
return nullptr;
}
I realize that I'll most likely get a lot of "you shouldn't do that because..." answers and they are most welcome and I'll probably totally agree with your reasoning, but I'm curious as to whether this is possible (as I envision it).
Is it possible to define a type of dynamic/generic object in C++ where I can dynamically create properties that are stored and retrieved in a key/value type of system? Example:
MyType myObject;
std::string myStr("string1");
myObject.somethingIJustMadeUp = myStr;
Note that obviously, somethingIJustMadeUp is not actually a defined member of MyType but it would be defined dynamically. Then later I could do something like:
if(myObject.somethingIJustMadeUp != NULL);
or
if(myObject["somethingIJustMadeUp"]);
Believe me, I realize just how terrible this is, but I'm still curious as to whether it's possible and if it can be done in a way that minimizes it's terrible-ness.
C++Script is what you want!
Example:
#include <cppscript>
var script_main(var args)
{
var x = object();
x["abc"] = 10;
writeln(x["abc"]);
return 0;
}
and it's a valid C++.
You can do something very similar with std::map:
std::map<std::string, std::string> myObject;
myObject["somethingIJustMadeUp"] = myStr;
Now if you want generic value types, then you can use boost::any as:
std::map<std::string, boost::any> myObject;
myObject["somethingIJustMadeUp"] = myStr;
And you can also check if a value exists or not:
if(myObject.find ("somethingIJustMadeUp") != myObject.end())
std::cout << "Exists" << std::endl;
If you use boost::any, then you can know the actual type of value it holds, by calling .type() as:
if (myObject.find("Xyz") != myObject.end())
{
if(myObject["Xyz"].type() == typeid(std::string))
{
std::string value = boost::any_cast<std::string>(myObject["Xyz"]);
std::cout <<"Stored value is string = " << value << std::endl;
}
}
This also shows how you can use boost::any_cast to get the value stored in object of boost::any type.
This can be a solution, using RTTI polymorphism
#include <map>
#include <memory>
#include <iostream>
#include <stdexcept>
namespace dynamic
{
template<class T, class E>
T& enforce(T& z, const E& e)
{ if(!z) throw e; return z; }
template<class T, class E>
const T& enforce(const T& z, const E& e)
{ if(!z) throw e; return z; }
template<class Derived>
class interface;
class aggregate;
//polymorphic uncopyable unmovable
class property
{
public:
property() :pagg() {}
property(const property&) =delete;
property& operator=(const property&) =delete;
virtual ~property() {} //just make it polymorphic
template<class Interface>
operator Interface*() const
{
if(!pagg) return 0;
return *pagg; //let the aggregate do the magic!
}
aggregate* get_aggregate() const { return pagg; }
private:
template<class Derived>
friend class interface;
friend class aggregate;
static unsigned gen_id()
{
static unsigned x=0;
return enforce(++x,std::overflow_error("too many ids"));
}
template<class T>
static unsigned id_of()
{ static unsigned z = gen_id(); return z; }
aggregate* pagg;
};
template<class Derived>
class interface: public property
{
public:
interface() {}
virtual ~interface() {}
unsigned id() const { return property::id_of<Derived>(); }
};
//sealed movable
class aggregate
{
public:
aggregate() {}
aggregate(const aggregate&) = delete;
aggregate& operator=(const aggregate&) = delete;
aggregate(aggregate&& s) :m(std::move(s.m)) {}
aggregate& operator=(aggregate&& s)
{ if(this!=&s) { m.clear(); std::swap(m, s.m); } return *this; }
template<class Interface>
aggregate& add_interface(interface<Interface>* pi)
{
m[pi->id()] = std::unique_ptr<property>(pi);
static_cast<property*>(pi)->pagg = this;
return *this;
}
template<class Inteface>
aggregate& remove_interface()
{ m.erase[property::id_of<Inteface>()]; return *this; }
void clear() { m.clear(); }
bool empty() const { return m.empty(); }
explicit operator bool() const { return empty(); }
template<class Interface>
operator Interface*() const
{
auto i = m.find(property::id_of<Interface>());
if(i==m.end()) return nullptr;
return dynamic_cast<Interface*>(i->second.get());
}
template<class Interface>
friend aggregate& operator<<(aggregate& s, interface<Interface>* pi)
{ return s.add_interface(pi); }
private:
typedef std::map<unsigned, std::unique_ptr<property> > map_t;
map_t m;
};
}
/// this is a sample on how it can workout
class interface_A: public dynamic::interface<interface_A>
{
public:
virtual void methodA1() =0;
virtual void methodA2() =0;
};
class impl_A1: public interface_A
{
public:
impl_A1() { std::cout<<"creating impl_A1["<<this<<"]"<<std::endl; }
virtual ~impl_A1() { std::cout<<"deleting impl_A1["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_A2: public interface_A
{
public:
impl_A2() { std::cout<<"creating impl_A2["<<this<<"]"<<std::endl; }
virtual ~impl_A2() { std::cout<<"deleting impl_A2["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
};
class interface_B: public dynamic::interface<interface_B>
{
public:
virtual void methodB1() =0;
virtual void methodB2() =0;
};
class impl_B1: public interface_B
{
public:
impl_B1() { std::cout<<"creating impl_B1["<<this<<"]"<<std::endl; }
virtual ~impl_B1() { std::cout<<"deleting impl_B1["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_B2: public interface_B
{
public:
impl_B2() { std::cout<<"creating impl_B2["<<this<<"]"<<std::endl; }
virtual ~impl_B2() { std::cout<<"deleting impl_B2["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
};
int main()
{
dynamic::aggregate agg1;
agg1 << new impl_A1 << new impl_B1;
dynamic::aggregate agg2;
agg2 << new impl_A2 << new impl_B2;
interface_A* pa = 0;
interface_B* pb = 0;
pa = agg1; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
agg2 = std::move(agg1);
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
return 0;
}
tested with MINGW4.6 on WinXPsp3
Yes it is terrible. :D
It had been done numerous times to different extents and success levels.
QT has Qobject from which everything related to them decends.
MFC has CObject from which eveything decends as does C++.net
I don't know if there is a way to make it less bad, I guess if you avoid multiple inheritance like the plague (which is otherwise a useful language feature) and reimplement the stdlib it would be better. But really if that is what you are after you are probably using the wrong language for the task.
Java and C# are much better suited to this style of programming.
#note if I have read your question wrong just delete this answer.
Check out Dynamic C++
This list, has to hold functions, they might be from different namespaces and even methods of instanced classes.
This list will then be iterated and all the functions and methods called. It would be nice if they could contain arguments also.
I was thinking on using a std::vector, but I suspect that I am far from correct in that guess.
What approach do you recommend me? All help is welcome.
You could use std::function and std::bind if your compiler already supports it.
#include <functional>
#include <vector>
void x(int) {}
void y() {}
class Z {
public:
void z() {}
};
int main(int argc, char *argv[])
{
typedef std::function<void ()> VoidFunc;
typedef std::vector<VoidFunc> FuncVector;
FuncVector functions;
functions.push_back(std::bind(&x, 1));
functions.push_back(&y);
Z z1;
functions.push_back(std::bind(&Z::z, z1));
for(FuncVector::iterator i = functions.begin(); i != functions.end(); i++) {
(*i)();
}
return 0;
}
Have all of your functions implement the Command Pattern.
Your list becomes a
std::list<Command>
As you iterate over the list, you invoke the Execute() method of each list item.
For example, say you have a simple Command interface called Commander:
class Commander
{
public:
virtual ~Commander;
virtual void Execute();//= 0;
};
And you have three objects that you want to put in your list: A Greyhound, a Gyrefalcon, and a Girlfriend. Wrap each in a Commander object that calls the object's function of interest. The Greyhound runs:
class RunGreyhound: public Commander
{
public:
void Execute()
{
mGreyhound->Run();
}
private:
Greyhound* mGreyhound;
};
The Gyrefalcon flies:
class RunGyrefalcon: public Commander
{
public:
void Execute()
{
mGyrefalcon->Fly( mGyrefalcon->Prey() );
}
private:
Gyrefalcon* mGyrefalcon;
};
And the Girlfriend squawks:
class RunGirlfriend: public Commander
{
public:
void Execute()
{
mGirlfriend->Squawk( mGirlfriend->MyJunk(), mGirlfriend->Mytrun() );
}
private:
Girlfriend* mGirlfriend;
};
Stuff the Commander objects in your list. Now you can iterate over them and invoke each element's Execute() method:
std::list<Commander> cmdlist;
RunGreyhound dog;
cmdlist.push_back( dog );
RunGyrefalcon bird;
cmdlist.push_back( bird );
RunGirlfriend gurl;
cmdlist.push_back( gurl );
for ( std::list<Commander>::iterator rit = cmdlist.begin(); rit != cmdlist.end(); ++rit )
{
rit->Execute();
}
If you don't want to use an existing solution such as boost::function, you will need to create a base class that represents a function, and then derived classes that wrap various sources of functions. For example:
#include <iostream>
#include <list>
using std::cout;
using std::list;
struct Function {
virtual ~Function() { }
virtual void operator()() = 0;
};
struct PlainFunction : Function {
PlainFunction(void (*function_ptr_arg)()) : function_ptr(function_ptr_arg) { }
virtual void operator()() { (*function_ptr)(); }
void (*function_ptr)();
};
template <typename T>
struct MethodFunction : Function {
MethodFunction(T &obj_arg,void (T::*method_ptr_arg)())
: obj(obj_arg), method_ptr(method_ptr_arg)
{
}
virtual void operator()() { (obj.*method_ptr)(); }
T &obj;
void (T::*method_ptr)();
};
void f()
{
cout << "Called f()\n";
}
struct A {
void f() { cout << "Called A::f()\n"; }
};
int main(int argc,char **argv)
{
list<Function *> functions;
functions.push_back(new PlainFunction(f));
A a;
functions.push_back(new MethodFunction<A>(a,&A::f));
list<Function *>::iterator i = functions.begin();
for (;i!=functions.end();++i) {
(*(*i))();
}
while (!functions.empty()) {
Function *last_ptr = functions.back();
functions.pop_back();
delete last_ptr;
}
}