473,408 Members | 2,734 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,408 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 22280
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...
0
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...
0
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...
0
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,...

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.