473,426 Members | 1,780 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,426 software developers and data experts.

difference between templates and macros

San
hi there,

I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.

can anyone please explain advantages of one over the other ?

Thanks in advance -
San

Aug 16 '06 #1
11 22285
San wrote:
hi there,

I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.

can anyone please explain advantages of one over the other ?

Thanks in advance -
San
Hi San,

In C++ there is a major difference between a template and a macro. A
macro is merely a string that the compiler replaces with the value that
was defined. E.g.
#define STRING_TO_BE_REPLACED "ValueToReplaceWith"

A template is a way to make functions independent of data-types. This
cannot be accomplished using macros. E.g. a sorting function doesn't
have to care whether it's sorting integers or letters since the same
algorithm might apply anyway.

Hope this helped.

Aug 16 '06 #2
San wrote:
hi there,

I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.
Not realy, macros are expanded by the preprocessor, the compiler doesn't
see them. They are simple test substitution.
can anyone please explain advantages of one over the other ?
The only practical advantage of macros is the ability to call a function
with __FILE__ and __LINE__ for debugging.

Macros don't have any scope, being simple text substitution. Macros
can't be stepped into with a debugger. Macros can't be specialised.
Macros aren't type safe, the list goes on.

--
Ian Collins.
Aug 16 '06 #3
San posted:
hi there,

I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.

can anyone please explain advantages of one over the other ?

Thanks in advance -
San

If you want to specialise a macro function, you have to pre-define it
outside of the function in which it's used. Consider a function which
returns the length of a null-terminated array:

#include <cstddef>
using std::size_t;

#define DEF(Type)\
size_t LenNullTerm(Type const *p)\
{\
size_t i = 0;\
while(*p++) ++i;\
return i;\
}

If we want to use this function on three different types, we have to pre-
define them as follows:

DEF(char)
DEF(double)
DEF(int)

int main()
{
int array1[5] = {3,4};

char array2[5] = {'a','b','c'};

double array3[5] = {5.2,3.4,6.2};

LenNullTerm(array1);
LenNullTerm(array2);
LenNullTerm(array3);
}

With templates, there's no need to pre-define the function with "DEF".
Instead, we just have:

#include <cstddef>

template<class T>
size_t LenNullTerm(T const *p)
{
size_t i = 0;
while(*p++) ++i;
return i;
}

int main()
{
int array1[5] = {3,4};

char array2[5] = {'a','b','c'};

double array3[5] = {5.2,3.4,6.2};

LenNullTerm(array1);
LenNullTerm(array2);
LenNullTerm(array3);
}

--

Frederick Gotham
Aug 16 '06 #4
Ian Collins <ia******@hotmail.comwrote:
San wrote:
>I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.
Not realy, macros are expanded by the preprocessor, the compiler doesn't
see them. They are simple test substitution.
#define test text
>can anyone please explain advantages of one over the other ?
The only practical advantage of macros is the ability to call a function
with __FILE__ and __LINE__ for debugging.
There are also the token pasting and string quoting abilities, though I
rarely if ever use those either.
Macros don't have any scope, being simple text substitution. Macros
can't be stepped into with a debugger. Macros can't be specialised.
Macros aren't type safe, the list goes on.
I agree.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Aug 16 '06 #5
In article <ec*********@news-int.gatech.edu>,
Marcus Kwok <ri******@gehennom.invalidwrote:
>Ian Collins <ia******@hotmail.comwrote:
>San wrote:
>>I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.
Not realy, macros are expanded by the preprocessor, the compiler doesn't
see them. They are simple test substitution.

#define test text
>>can anyone please explain advantages of one over the other ?
The only practical advantage of macros is the ability to call a function
with __FILE__ and __LINE__ for debugging.

There are also the token pasting and string quoting abilities, though I
rarely if ever use those either.
>Macros don't have any scope, being simple text substitution. Macros
can't be stepped into with a debugger. Macros can't be specialised.
Macros aren't type safe, the list goes on.

I agree.
Macros do have scope, the problem (at least one of them) is that
as the preprocessor is effectively a seperate language intertwinded
with C++ (and C) it has its own view of things, so it's a different
kind of scope, etc.
--
Greg Comeau / 20 years of Comeauity! Intel Mac Port now in alpha!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 16 '06 #6
San
Hello All -

Many thanks for replying to my query, it was helpful to some extent.
Macros don't have any scope, being simple text substitution. Macros
can't be stepped into with a debugger. Macros can't be specialised.
Macros aren't type safe, the list goes on.
I agree to the advantages mentioned above, but then I was thinking of
some more compelling advangates as oppose to the complexity the
templates beings in.

Specialization - as explained by Frederick , in my opinion (may be
incorrect), may not bring the compelling advantages either, as there
would be already the functionality available in the "C" standard. So,
just was looking it from the larger advantages from the C++ standards
perspective.

Once again - many thanks for all your replies.

Regards,
San

Ian Collins wrote:
San wrote:
hi there,

I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.
Not realy, macros are expanded by the preprocessor, the compiler doesn't
see them. They are simple test substitution.
can anyone please explain advantages of one over the other ?
The only practical advantage of macros is the ability to call a function
with __FILE__ and __LINE__ for debugging.

Macros don't have any scope, being simple text substitution. Macros
can't be stepped into with a debugger. Macros can't be specialised.
Macros aren't type safe, the list goes on.
--
Ian Collins.
Aug 17 '06 #7
In article <11**********************@i42g2000cwa.googlegroups .com>,
San <sa*******@gmail.comwrote:
>Ian Collins wrote:
>San wrote:
hi there,

I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.
Not realy, macros are expanded by the preprocessor, the compiler doesn't
see them. They are simple test substitution.
can anyone please explain advantages of one over the other ?
The only practical advantage of macros is the ability to call a function
with __FILE__ and __LINE__ for debugging.

Macros don't have any scope, being simple text substitution. Macros
can't be stepped into with a debugger. Macros can't be specialised.
Macros aren't type safe, the list goes on.

Many thanks for replying to my query, it was helpful to some extent.
>Macros don't have any scope, being simple text substitution. Macros
can't be stepped into with a debugger. Macros can't be specialised.
Macros aren't type safe, the list goes on.

I agree to the advantages mentioned above, but then I was thinking of
some more compelling advangates as oppose to the complexity the
templates beings in.

Specialization - as explained by Frederick , in my opinion (may be
incorrect), may not bring the compelling advantages either, as there
would be already the functionality available in the "C" standard. So,
just was looking it from the larger advantages from the C++ standards
perspective.

Once again - many thanks for all your replies.
ANSTAAFL. That said, the premise is that something like
template is known to the compiler and so there is a shot at
better elbow rubbing among features, stronger type safety,
matching efficiency, etc. Also, note that to some extent,
template authoring deals with a more fine grained library
authoring, with is not always what everybody needs to be doing.
IOWs, it may not necessarily be something a beginning should be
jumping right into. As with most things there are compromises
which need to be considered and delicate balances.
--
Greg Comeau / 20 years of Comeauity! Intel Mac Port now in alpha!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 17 '06 #8
Someone wrote:
The only practical advantage of macros is the ability to call a function
with __FILE__ and __LINE__ for debugging.
Also use them for anything a higher-level thing can't do:

- stringerization
- token pasting
- conditional compilation

Now that we have explained why C++ templates are not C++ macros, it's time
to explain why C++ templates are "macros", according to the term's general
computer science meaning.

A template is defined to expand as if it were text, so the compiler can then
compile the result. Naturally this is more typesafe than a C++ macro. But
the actual definition of expansion leaves the intermediate text-like thing
open to subtle bugs and issues. Most notably the 'typename' keyword had to
be introduced to patch the biggest set of bugs.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Aug 17 '06 #9

San wrote:
hi there,

I am new to c++ and tryig to learn the basics of the c++ concepts.
While I was reading the templates, I realize that the templates are a
syntax that the compilar expands pased upon the type specified. This is
much similar like a macro expansion in C.

can anyone please explain advantages of one over the other ?

Thanks in advance -
San
A macro invocation translates into a arbitrary sequence of token.
The parameters passed to a macro are also arbitrary sequences
of tokens. Translation of macros can be thought of as a
phase in compilation that takes place between tokenization
and parsing. This is why macros can't be scoped by classes,
namespaces, etc., because those haven't been parsed yet.
The simplicity and flexibility of a macro is exactly what's
called for some purposes. But when someone sees a macro
in some code they're trying to understand, they have to consider
alot of possibilities as to what it might be doing. So avoiding the
use of macros will make you more popular with people who
have to understand your code. Said people as thus less
likely to tell your boss that you suck.

Template translation is part of parsing, and can't be thought
of as a separate phase. When the parser comes to a
template invocation, it wormholes up to file scope and
expands the template (with an implicit "using" declaration
of the partially-defined namespaces containing the
invocation). It's this wormholing behavior that gives
templates an importance that goes far beyond just
being well-behaved macros.

Aug 17 '06 #10
On Thu, 17 Aug 2006 13:31:12 GMT, "Phlip" <ph******@yahoo.comwrote:
>Now that we have explained why C++ templates are not C++ macros, it's time
to explain why C++ templates are "macros", according to the term's general
computer science meaning.
Hear hear!
>A template is defined to expand as if it were text, so the compiler can then
compile the result. Naturally this is more typesafe than a C++ macro.
Actually, templates are untyped (what is the type of T?). The
seemingly typesafe aspect comes into play because the template macro
expansion may result in something that is not compilable, producing
the well-known heaps of error messages.

Best wishes,
Roland Pibinger
Aug 17 '06 #11
Roland Pibinger wrote:
On Thu, 17 Aug 2006 13:31:12 GMT, "Phlip" <ph******@yahoo.comwrote:
>>Now that we have explained why C++ templates are not C++ macros, it's time
to explain why C++ templates are "macros", according to the term's general
computer science meaning.

Hear hear!
>>A template is defined to expand as if it were text, so the compiler can
then compile the result. Naturally this is more typesafe than a C++ macro.

Actually, templates are untyped (what is the type of T?).
Well, if you have

template < int T >
struct ...

then T is an int, and if you have

template < typename T >
struct ...

then T better be a typename and if you have

template < template < class T >
struct ...

then T has to be a template taking one typename parameter.
The
seemingly typesafe aspect comes into play because the template macro
expansion may result in something that is not compilable, producing
the well-known heaps of error messages.
That too, but template parameters are typed. It just so happens that the
types typename and template are (unfortunately?) not available for run-time
variables.
Best

Kai-Uwe Bux
Aug 17 '06 #12

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

Similar topics

5
by: Andreas Micheler | last post by:
Hi, I have several long complex C macros in the math module of aUCBLogo like #define _XFUNC_primitive(NAME)\ NodeP _##NAME(PairPP arg)\ { ((ObjectP)(arg))->var()->NAME( arg );\ return...
45
by: Lindsay | last post by:
I was just reading another post when someone commented that the code was C and not C++. What are the differences? (Examples?) The answer does not affect my programming but would help to know if I...
25
by: Ted | last post by:
I'm putting the posts that follow here (hopefully they will follow here!) because they were rejected in comp.lang.c++.moderated. It behooves anyone reading them to first read the the thread of the...
28
by: NewToCPP | last post by:
Hi, I am just trying to find out if there is any strong reason for not using Templates. When we use Templates it is going to replicate the code for different data types, thus increasing the...
2
by: david wolf | last post by:
My understanding is that cstdio basically is the same as stdio.h except the functions are in a namspace called std. However when I take a look at the content of the file cstdio, it has the...
104
by: JohnQ | last post by:
Well apparently not since one can step thru template code with a debugger. But if I was willing to make the concession on debugging, templates would be strictly a precompiler thing? I have a...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.