TCLUG Development Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [TCLUG-DEVEL:65] null ptr excpetion - java
On Thu, Feb 10, 2000 at 06:10:10PM -0600, erick@pagelab.net wrote:
> Well, let me see, C++? I put java on the subject list, and I said
> "kind of a template". Hmmm, sorry for the confusion. I guess I
> thought a template was something you modeled after. I guess I am
> wrong. What is a template?
In C++ a template is a sort of highly refined macro. Here is an
example C++ template:
template <class T> const T &max(const T &a, const T &b)
{
return((a > b) ? a : b);
}
This doesn't result in any code itself, but if you have code
like this:
double fred = 1, barney = 2;
int wilma = 3, bettey = 4;
max(fred, barney);
max(wilma, bettey);
This will cause the compiler to 'instantiate' the template,
which basically means expanding the macro to have double, or int in
place of T. This creates two version of 'max'. One is:
const double &max(const double &a, const double &b)
{
return((a > b) ? a : b);
}
and the other is:
const int &max(const int &a, const int &b)
{
return((a > b) ? a : b);
}
This mechanism allows you to write a bunch of code that operates
similarily on many different types. For example, in Java, you have
java.lang.Vector, which holds Object references. If it were a template,
you would specify what type it held when you declared it. The compiler
would create that type at compile time, and you wouldn't have to do any
casting in code which used it.
In my opinion, templates are way overused. A lot of people use
them to provide 'inheritance by name' which allows you to treat two
types the same as long as they define the same methods. They don't need
an inheritance relationship between them. IMHO, this is sloppy design.
Have fun (if at all possible),
--
Its name is Public Opinion. It is held in reverence. It settles everything.
Some think it is the voice of God. Loyalty to petrified opinion never yet
broke a chain or freed a human soul. ---Mark Twain
-- Eric Hopper (hopper@omnifarious.mn.org http://omnifarious.mn.org/~hopper) --
PGP signature