Re: Building the name of an executable function
On Aug 21, 8:53 am, mlimber <mlim...@gmail.com> wrote:
On Aug 21, 9:48 am, Miner Jeff <jeff.p.bled...@lmco.com> wrote:
I need to build the name of a function from data in a text file. For
example, after reading the variables 'FCTN_PREFIX' AND 'FCTN_SUFFIX'
from the text file, I need to execute the function:
FCTN_PREFIX & 'TXT1' & FCTN_SUFFIX & 'TXT2';
where TXT1 and TXT2 are hardcoded text; & indicates concatenation.
I assume I could concatenate the text to build the function name and
give it a variable name but how can I then execute that function?
I just posted on this topic on another thread. You might use std::map
to associate your string with a function, something like:
typedef void (*Fn)();
typedef std::map<std::string,Fn> MyMap;
MyMap myMap; // global for the sake of simplicity
void Hello() {/*...*/}
void World() {/*...*/}
void Call( const std::string& str )
{
MyMap::const_iterator it = myMap.find( str );
if( it != myMap.end() )
{
it->second();
}
}
int main()
{
myMap[ "hello" ] = &Hello;
myMap[ "world" ] = &World;
Call( "hello" );
Call( "world" );
}
Cheers! --M
Thanks. I had asked one of my colleagues if I could 'build' a function
name and he said the function names needed to be defined before
compiling; he explained that an interpreter type of program could do
that.
After I showed him your response, he agreed that your method would
work. In fairness to him, he is correct in his original assertion that
simply building function names during execution won't work.
Next question: I'll have to map several hundred of these functions. To
keep my main code much simpler, what would I have to do to move the
mapping code to a unique C++ file?
Thanks,
Jeff