Re: Initialising a map
On Jun 27, 3:06 pm, Angus <anguscom...@gmail.com> wrote:
Should I be able to do something like this:
static const std::map<RequestType, string> RequestMap = {
{ AOpenEx, "AOpenEx" },
{ AClose, "AClose" },
{ ARegister, "ARegister" },
{ AUnregister, "Unregister" } };
RequestType is an enum.
I can't compile it. Or can I not initialise with an array
like this?
You can initialize it with an array. You can't use agglomerate
initialization on it, however, because it isn't an agglomerate.
The general solution is to declare something like:
typedef std::map< RequestType, string >
RequestMap ;
struct RequestMapInitializer
{
RequestType key ;
char const* value ;
operator RequestMap::value_type() const
{
return RequestMap::value_type(
key, std::string( value ) ;
}
}
RequestMapInitializer const initializer[] =
{
{ AOpenEx , "AOpenEx" },
{ AClose , "AClose" },
{ ARegister , "ARegister" },
{ AUnregister, "Unregister" },
}
RequestMap requestMap( begin( initializer ),
end( initializer ) ) ;
(with the usual definitions for begin and end, of course).
For small things like this, I find just using a C style array
and std::find simpler, and perfectly adequate. So I wrote a
template class StaticMap
template< typename MappedType,
typename KeyType = char const* >
struct StaticMap
{
KeyType key ;
MappedType value ;
class Matcher
{
public:
explicit Matcher( KeyType const& targetKey )
: myKey( targetKey )
{
}
bool operator()( StaticMap const& obj )
const
{
return myKey == obj.key ;
}
private:
KeyType myKey ;
} ;
static StaticMap const*
find(
StaticMap const* begin,
StaticMap const* end,
KeyType const& value )
{
return std::find_if( begin, end, Matcher( value ) ) ;
}
} ;
(Originally, the key type was always char const*, since that
corresponded to most of my uses. That's why it's unexpectedly
the second template argument.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34