Re: template #if preprocessor
On Aug 8, 2:50 pm, kRyszard <kry...@gmail.com> wrote:
how to make the following code work:
template<class TYPE>
void f2(char *buffer, TYPE *outer) {
// do something ...
// ...
#if (TYPE == int)
*outer = atoi(buffer);
#endif
#if (TYPE == double)
*outer = atof(buffer);
#endif
#if (TYPE == char)
strcpy(outer, buffer);
#endif
// release memory here
// ...
None of my business, of course, but what memory are you
releasing?
return;
}
it is not working but maybe you know how to modify it to make it
work...
In this precise case, of course, the obvious solution is:
template< typename T >
void
f2( char const* buffer, T* dest )
{
std::istrstream s( buffer, strlen( buffer ) ) ;
s >> *dest ;
// Error checking here...
}
If this is just an example of a more general problem, of
course...
template< typename T >
struct Cvt
{
static T convert( char const* buffer ) ;
} ;
template< typename T >
void
f2( char const* buffer, T* dest )
{
// ...
*dest = Cvt< T >::convert( buffer ) ;
// ...
}
template<>
struct Cvt< int >
{
static int convert( char const* buffer )
{
return atoi( buffer ) ;
}
} ;
template<>
struct Cvt< double >
{
static int convert( char const* buffer )
{
return atof( buffer ) ;
}
} ;
// ...
--
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