473,804 Members | 2,201 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

template #if preprocessor

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;
}

it is not working but maybe you know how to modify it to make it
work...
K

Aug 8 '07 #1
5 2863
kRyszard 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;
}

it is not working but maybe you know how to modify it to make it
work...
K
macro and preprocessor are done during preprocessing time,
template initiation is done compile-time, which is after
preprocessing-time, you can't mix them up
Aug 8 '07 #2
kRyszard 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;
}

it is not working but maybe you know how to modify it to make it
work...
As Alf mentioned, boost::lexical_ cast maybe work well with only the
integral types in your case; from the OP, when the type is char, the
function just wants to do a string copy.

So my suggestion is don't borrow template if it's only because it's fancy.

you can do the integral types with template using lexical_cast, and
write an additional overloaded function to handle type char
#include <boost/lexical_cast.hp p>
#include <iostream>

using namespace boost;
using namespace std;

template <typename T>
T f2(char const* buffer) {
return lexical_cast<T> (buffer);
}

void f2(char const* buffer, char* out) {
strcpy(out, buffer);
}

int main()
{
cout << f2<int>("1000") << endl;
cout << f2<double>("1.0 ") << endl;

char out[100];
f2("hello", out);
cout << out << endl;
}
Aug 8 '07 #3
joe
On Aug 8, 8:50 am, kRyszard <kry...@gmail.c omwrote:
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.

Aug 8 '07 #4
joe
Ahhh, I've been Googled. Didn't mean to submit the last message.

Anyway, I was going to recommend just a series of function overloads
instead of the templates.

void f2(char * buffer, char * out)
{
// handle char *
}
void f2(char * buffer, int * out)
{
*out = atoi(buffer);
}

And so forth. No need for templates for this usage. However, I did
give in the previous, not quite edited in the way I would wish
message, a way to do it with templates. :) I'm quitting now before I
do some other weird edit and send thing.

joe

Aug 8 '07 #5
On Aug 8, 2:50 pm, kRyszard <kry...@gmail.c omwrote:
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:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Aug 9 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1871
by: David Lindauer | last post by:
suppose I have this: template <class T> class myclass { T a ; #ifdef PREPROC_SYMBOL T b; #endif } ;
10
5543
by: Clay_Culver | last post by:
I have heard that it is possible to use classes + template magic to make standalone functions (or maybe just a functor which acts like a function) which can accept variable length arguments without using the elipse. For example, a funciton could take in 1 known type, then a variable list of other parameters: ReturnValueClass rvc = someFunction("Some known type", 1, 0.2, "string"); ReturnValueClass rvc2 = someFunction("Some known type...
3
1780
by: martin.druon | last post by:
Hi, I created a template class to represent hypermatrix. I would like to add methods where the number of parameters are checked during the compilation time. For example : template <size_t dim> class Matrix { protected :
3
1743
by: DougS | last post by:
I would like to create HTML pages using embedded "markers" which represent HTML code that is common to all of my pages. I need a utility which will replace these "markers" with the associated code. This would be a great way to update banners and navigation bars without using frames. Thanks in advance for any ideas.
4
1832
by: Howard Gardner | last post by:
// I think that there is no way to write the template "cant_write_me" in // this example. Would love to be wrong. // one of many approaches that won't work template< template< typename class struct cant_write_me{}; template< template< typename, typename class struct cant_write_me{}; template< typename struct arity_one{}; template< typename, typename struct arity_two{};
9
2754
by: Mike | last post by:
Hi, Just a simple question: why the compiler doesn't report error when accessing a private member function inside a function having template type ? For example: #include<iostream> using namespace std;
2
2010
by: adrian.hawryluk | last post by:
Hi everyone, I've been using templates for a while, but I'm not at full power yet (knowledge=power) ;). Does anyone know where I can get information on this 'new' template usage? template<a (b, c, d)> Does one define it like:
14
11750
by: Jess | last post by:
Hello, I was told that if I have a template class or template function, then the definitions must be put into the header file where I put the declarations. On the other hand, it is generally good to put source code and declaration into separate files (.h head filer and .cpp source file). What can I do to template functions/classes? Do I have to put them all into one header file? Thanks,
5
3623
by: iapx86 | last post by:
My parser project calls for a computed goto (see code below). The C preprocessor delivers the desired result, but is ugly. Template metaprogramming delivers results I do not understand. Can anyone explain why loop unrolling doesn't play well with templates? Or better, can someone submit a code fragment to get desired results? Here are the command-lines I use to generate code: "g++ -DTEMPLATE=0 -o gotofun0 gotofun.cpp" works exactly as...
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10600
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10352
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7642
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5535
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4313
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.