Re: template #if preprocessor
On Aug 8, 8:50 am, 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
// ...
return;
}
First thing, as was mentioned else where, the #if statements are
preprocessor statements and are applied well before the template
instantiation mechanism comes into play. Second, for what you are
doing, you can just use function overloads to implement your
conversions. That is,
void f2(char * buffer, char * out)
{
}
If you are going to mess with templates, I would suggest "C++
Templates" by Vandevoorde and Josuttis, however I can give you a
couple of pointers to get you started.
First, consider an existing solution such as boost::lexical_cast
(www.boost.org). The only problem with it is that it uses streams as
it's underpinnings and can therefore be slow compared to atoi() etc.
Most often though, this kind of conversion isn't done often enough to
warrant more effort than that.
If you feel that you are in the category where performance matters or
if you are just doing this as an exercise to learn templates, then I
can offer the following advice.
1) All of the # prefixed statements are C++ preprocessor statements
and don't work the way you are trying above.
2) The way you would set up your template specializations would look
like:
template <typename TYPE>
void f2(char * buffer, TYPE *outer)
{
// Do something generic like whine about this conversion not being
taken into account or possibly
// use #error
}
// Now specialize for the cases we know how to handle
template <>
void f2<int>(char * buffer, int * outer)
{
// convert to int
*outer = atoi(buffer);
}
template <>
void f2<double>(char * buffer, double * outer)
{
// convert to double
*outer = atof(buffer);
}
// the rest follow a similar pattern
Now, I didn't change the interface from what you posted, but
somewhere, you will want to verify that someone didn't just ask to
convert "Hello World" into a double or whatever, but since I don't
know your inputs I won't say much else about that.