473,883 Members | 1,663 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 22393
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_RE PLACED "ValueToReplace With"

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(Typ e 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(arr ay1);
LenNullTerm(arr ay2);
LenNullTerm(arr ay3);
}

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(arr ay1);
LenNullTerm(arr ay2);
LenNullTerm(arr ay3);
}

--

Frederick Gotham
Aug 16 '06 #4
Ian Collins <ia******@hotma il.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*********@ne ws-int.gatech.edu> ,
Marcus Kwok <ri******@gehen nom.invalidwrot e:
>Ian Collins <ia******@hotma il.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************ **********@i42g 2000cwa.googleg roups.com>,
San <sa*******@gmai l.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.

Specializati on - 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

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

Similar topics

5
1900
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 Unbound;\ }
45
4176
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 need to post a question.
25
3350
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 same subject in clc++m to get the more of the context. Ted
28
2654
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 executable size. This should not cause any performance issue. So, is it safe to say that if I can offered to have bigger image size I can go ahead and use Templates with out worrying about any other issues?
2
14602
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 following lines inside only: -------content of cstdio on red hat linux enterprise 3---- #ifndef __CSTDIO__ #define __CSTDIO__ #include <stdio.h> #endif
104
4657
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 feeling the answer I'm going to get back will be "no, because templates have taken on a life of their own since their original conception and now also affect compiler implementation" (read: not good, IMO. John
0
9933
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
9781
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
11121
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
10734
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...
0
9564
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7114
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5982
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4606
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
3230
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.