Quote:Original post by Volte6
<?php$person1 = "Dylan";$i=1;$customVar = "person".$i;echo( ${$customVar} );// Result:// Dylan?>
Is there a similar technique in c++? In Foxpro they have something called Macro Substitution which does that as well.
Sort of, but not quite. Here's the closest (simple) equivilant I can think of:
std::map< std::string , std::string > vars;vars["person1"] = "Dylan";vars["i"] = "1";//alternative(s)://= boost::lexical_cast< std::string >( 1 );vars["customVar"] = std::string( "person" ) + vars["i"];//alternative(s)://= boost::str( boost::format("person%1%") % vars["i"] );//= boost::str( boost::format("person%1%") % 1 );//= std::string( "person" ) + boost::lexical_cast< std::string >( 1 )std::cout << vars[ vars["customVar"] ];
That is, you can't directly access the named variables of C++, but you can create a layer of indirection that will achieve the same effect. Managing this kind of thing can get hairy with complex types (read: custom classes with submembers to access). If you want to get into that I might suggest looking into
boost::any. Note my ample use of the boost library in my alternatives examples - it's a wonderful library that is worth looking into :).
Also, to provide a poor example alternative, to explain some how you can add this effect after the fact:
std::string person1 = "Dylan";std::map< std::string , std::string * > vars;vars["person1"] = &person1std::string customVar = "person"; customVar += "1";assert( vars[ customVar ] );std::cout << *vars[ customVar ];
Note: the reason there's only one vars[...] statement in this example is because "customVar" is an actual variable instead of a string to be used to access the vars[] array. If you were werid, you could replace the last 2 lines with:
std::string customVar = "person"; customVar += "1";
vars[ "customVar" ] = &customVar
assert( vars[ "customVar" ] );
assert( vars[ *vars[ "customVar" ] ] );
std::cout << *vars[ *vars[ "customVar" ] ];
[Edited by - MaulingMonkey on March 17, 2005 12:36:11 AM]