Sorry I am new both to the community and c++, please be gentle.
To begin with, as this is to run on a microcontroller, memory and compiled code space are extremely valuable.
I have a requirement to take input from various sources and feed them into a central processing function. The rolled up parameters fed in are to be named, be of varying types and, allow for type checking, so they can be compared against criteria unknown at compile time. I have borrowed bits of code from here and there and come up with the following.
template <typename T_ty> struct TypeInfo { static const char * name; };
template <typename T_ty> const char * TypeInfo<T_ty>::name = "unknown";
#define MAKE_TYPE_INFO( type ) template <> const char* TypeInfo<type>::name= #type;
// Type-specific implementations.
MAKE_TYPE_INFO( int );
MAKE_TYPE_INFO( float );
MAKE_TYPE_INFO( String );
MAKE_TYPE_INFO( char * );
MAKE_TYPE_INFO( bool );
class ParaBase
{
public:
char* _type ;
char* _name;
void* _child;
const char* name() { return _name; }
ParaBase(){}
ParaBase(const char* name, const char* type, const void * child )
:
_name( (char*) name ),
_type( (char*) type ),
_child( (void*) child ) {}
template <class U>
bool is()
{
return ( TypeInfo<U>::name == _type );
}
};
template <class T>
class Para : public ParaBase
{
T _value;
public:
Para( const char* name, const T value )
:
ParaBase( name, TypeInfo<T>::name, this ),
_value( value )
{}
Para( ParaBase& paraBase )
:
ParaBase( paraBase._name, paraBase._type, this )
{}
operator T() { return _value; }
const T value() { return _value; }
template <class U>
U as()
{
return *( ( U *) _value );
}
};
To test it I do the following:-
ParaBase para[3];
para[0] = Para<char*>("Param-one", "Hi");
para[1] = Para<bool> ("Param-two", true);
para[2] = Para<float>("Param-three", 2.05);
I can feed para into a central function fine.
bool ok = para[1].is<bool>(); // is true
bool notok = para[1].is<char*>(); // is false
So type checking works, yeah!
Para<char*> testDownCast = ( Para<char*>) para[0] ;
char* orig = testDownCast.as<char*>();
Erm, not so good. Major fail here. My testDownCast pointer (if I am using the correct term) just contains junk. What am I doing wrong?
Any help would be gratefully received. Thanks in advance for helping a novice.