Gary Wessle wrote:
Quote:
"Victor Bazarov" <v.Abazarov@comAcast.netwrites:
>
Quote:
>Gary Wessle wrote:
Quote:
>>I have a group of functions which have the same signature.
>>void fun_n(void);
>>according to a conditional structure "be it if-else or switch-case"
>>I get to choose which one to run.
>>>
>>conditional structure verifies a short type and fires the fun_n in
>>its block.
>>>
>>is this a good candidate for a function pointer? I was googleing and
>>wanted to practice a bit but only if it is a better approach.
>>
>Depending on your condition[s] an array of pointers, or a 'std::map'
>of value/ptr-to-func pairs might actually be clearer than a bunch of
>'if/else' statements or a switch pile.
>>
>V
>
good idea. help me with it please.
>
>
class Type2 {
>
public:
void mine();
This is a non-static member function.
Quote:
>
};
>
void Type2::mine(){
cout << "mine pointer de-referenced" << endl;
}
>
>
class Type1 {
Type2 type2;
typedef void (*pf)();
This is a pointer to function. In you intended to assign &Type2::mine
to 'pf', you cannot. For that you need to declare 'pf' as a "pointer
to member of Type2":
typedef void (Type2::*pf)();
Quote:
std::vector<pfptr_fun;
public:
void fire();
>
};
>
Type1::Type1( Type2 t2 ):
type2( t2 ),
names("mine his hers theirs etc"),
...
{}
>
void Type1::fire(){
/* build a vector<stringfrom "names" above */
for each item in this vector
build the string to look like &mine and vec.push_back("&mine").
>
and fire it by *(vec[i]) i.e de-referenced element number i in the
vector.
>
but this is a string vector and not a <address of functionsvector.
>
how can I solve this in an elegant way.
There is no "elegant" way of solving it. Somewhere you will _have_
to have a bunch of 'if' statements and compare your strings to some
known values and then push the pointers to members into your vector.
What I actually proposed to you was a 'std::map', like this:
class Type1 {
...
std::map<std::string, pfmymap;
...
};
You will need to fill it in (the c-tor is a good place if 'mymap'
is non-static). You should also consider having it as a static data
member, and initialise it only once.
Filling it in should be similar to
mymap["mine"] = &Type1::mine;
and so on.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask