C
Christopher Benson-Manica
At the moment, I've got the following situation (not my code):
// Assume appropriate headers have been included
enum MyType { ctypeNone, ctypeA, ctypeB, ctypeC };
class MyBaseClass {
static MyBaseClass* Create( const char * );
static MyType PickAClass( const char * );
};
class TypeA : public MyBaseClass {
typeA( const char * );
};
class TypeB : public MyBaseClass {
typeB( const char * );
};
class TypeC : public MyBaseClass {
typeC( const char * );
};
// actual implementation of Type* constructors omitted
MyType MyBaseClass:ickAClass( const char *str ) {
// do secret voodoo with str
return ctypeA; // or ctypeB, or ctypeC, or ctypeNone
}
MyBaseClass* MyBaseClass::Create( const char *str ) {
switch( PickAClass(str) ) {
case ctypeA: return( new TypeA(str) );
case ctypeB: return( new TypeB(str) );
case ctypeC: return( new TypeC(str) );
default: return NULL;
}
}
(Here there are only 3 types - in the actual code, there are 20.)
Now, this setup works correctly, but it strikes me as being
distinctively suboptimal. I'd like to create an array of function
pointers to the Type* constructors, so I could just index into that
array instead of messing with a 21-case switch statement. I don't
suppose I can take the address of a constructor, right? If so, what
is its type? If not, and if it is in fact worth the effort to revamp
this code, what do you suggest?
// Assume appropriate headers have been included
enum MyType { ctypeNone, ctypeA, ctypeB, ctypeC };
class MyBaseClass {
static MyBaseClass* Create( const char * );
static MyType PickAClass( const char * );
};
class TypeA : public MyBaseClass {
typeA( const char * );
};
class TypeB : public MyBaseClass {
typeB( const char * );
};
class TypeC : public MyBaseClass {
typeC( const char * );
};
// actual implementation of Type* constructors omitted
MyType MyBaseClass:ickAClass( const char *str ) {
// do secret voodoo with str
return ctypeA; // or ctypeB, or ctypeC, or ctypeNone
}
MyBaseClass* MyBaseClass::Create( const char *str ) {
switch( PickAClass(str) ) {
case ctypeA: return( new TypeA(str) );
case ctypeB: return( new TypeB(str) );
case ctypeC: return( new TypeC(str) );
default: return NULL;
}
}
(Here there are only 3 types - in the actual code, there are 20.)
Now, this setup works correctly, but it strikes me as being
distinctively suboptimal. I'd like to create an array of function
pointers to the Type* constructors, so I could just index into that
array instead of messing with a 21-case switch statement. I don't
suppose I can take the address of a constructor, right? If so, what
is its type? If not, and if it is in fact worth the effort to revamp
this code, what do you suggest?