Reputation: 34645
I have some problems with C++. I build application using GAlib library (it's a C++ Library of Genetic Algorithm Components - http://lancet.mit.edu/ga/).
In one of examples (full code of example: http://lancet.mit.edu/galib-2.4/examples/ex6.C) author create function that initializes tree:
void TreeInitializer(GAGenome & c)
{
GATreeGenome<int> &child=(GATreeGenome<int> &)c;
// destroy any pre-existing tree
child.root();
child.destroy();
// Create a new tree with depth of 'depth' and each eldest node containing
// 'n' children (the other siblings have none).
int depth=2, n=2, count=0;
child.insert(count++,GATreeBASE::ROOT);
for(int i=0; i<depth; i++){
child.eldest();
child.insert(count++);
for(int j=0; j<n; j++)
child.insert(count++,GATreeBASE::AFTER);
}
}
He invoke function in that way:
genome.initializer(TreeInitializer);
and He don't pass an argument. When I trying pass argument to that function by changing declaration for example:
void TreeInitializer(GAGenome &, int deph);
Compiler shows me errors. I don't know how to invoke this function properly. I know it's related to reference but passing (or not passing) argument in that way is new to me.
How to pass more arguments to that function?
Upvotes: 0
Views: 119
Reputation: 7324
The line genome.initializer(TreeInitializer);
does not call TreeInitializer
- instead, it passes the pointer to that function to genome.initializer
, so it can call it with whatever arguments it needs/multiple times. If you want TreeInitializer
to accept more arguments, you need to modify the initializer
to accept a different type of function. It is probably defined as
void initializer(void (*f)(GAGenome&))
{
// ...
f(genome);
// ...
}
You need to change the argument type to void (*f)(GAGenome&, int)
and change the lines that call f
.
On the other hand, if you can't modify the initializer function but want to be able to specify the depth, then the best you can do is make a global variable that you set to whatever depth you need and have TreeInitializer
use that variable. It isn't a clean solution if you think global variables are evil, but it's your only choice if the initializer
doesn't let you supply any "context".
Upvotes: 2
Reputation: 12575
What you what to do in
GATreeGenome<int> &child=(GATreeGenome<int> &)c;
is a casting from a GAGenome to GATreeGenome . If you haven't a casting operator for this case, it won't work...
Upvotes: -1