Christoph said:
Jeff said:
You could use a hash instead of a map, but there is none in the
standard library. Are your programs meant to run on only a particular
system, or do they need the portability that comes with compliance to
the standard?
No. The question simply appeared, without a concrete problem to solve. I
am just wondering...
I simply wanted to know if there is a container or something that is
more suited to the task than map.
Something along template Metaprogramming that constructs a switch/lookup
table for me.
Maybe with some restrictions (only ints or something like that).
And maybe this is just a weird thought.
I thought of something along a fixed size map. Where the
objects/function pointers are inserted is calculated at compile time and
lookup is maybe a bit better than log n.
[Insertion is not really an issue, but the lookup should be as fast as
possible]
Virtual methods solve this problem like you just described (ok - it may
be a bit of s stretch).
This is what I mean : instead of using enums, use a class. Derive new
classes with a behaviour specific to that enum. In this ReallyBad(TM)
example there is a header describing a "Material" is and materials
affect the behaviour of "Heating" and "Bending". A Shape describes the
shape of an object and a material can "look into" the shape and change
it depending on how what material it is.
//
// Header
//
struct Shape;
struct Angle;
struct Temperature;
struct Material
{
virtual ~Material(){}
virtual void Bend( Shape &, const Angle & ) const = 0;
virtual void Heat( Shape &, const Temperature & ) const = 0;
bool operator== ( const Material & lhs ) const
{
return this == & lhs;
}
};
extern const Material & Glass;
extern const Material & Steel;
// materials.cpp
//
// Material details
//
namespace
{
struct Glass_Material : Material
{
virtual void Bend( Shape &, const Angle & ) const;
virtual void Heat( Shape &, const Temperature & ) const;
};
Glass_Material g_Glass_Material;
struct Steel_Material : Material
{
virtual void Bend( Shape &, const Angle & ) const;
virtual void Heat( Shape &, const Temperature & ) const;
};
Steel_Material g_Steel_Material;
};
const Material & Glass = g_Glass_Material;
const Material & Steel = g_Steel_Material;
// application.cpp
//
// application code - knows nothing about implementations
//
void DoSomthing( Shape & i_shape, const Temperature & i_temp, const
Angle & i_angle )
{
Glass.Heat( i_shape, i_temp );
Glass.Bend( i_shape, i_angle );
const Material & mat_1 = Glass;
const Material & mat_2 = Steel;
if ( mat_1 == mat_2 )
{
// glass can't be the same as steel
}
}