"Ian Lazarus" <no****@nowhere.com> a écrit dans le message de news:
qW******************@bgtnsc05-news.ops.worldnet.att.net...
Why are constraints needed? In C++, an attempt to use a non-existing
method will cause a compiler error. Isn't that true in C# also?
If you're speaking about Generics constraints, there are IMHO 2 main reasons
for that :
- Generics syntax and semantic is checked before the generic is instanciated
(generics are instanciated at run time, not at compile time). Therefore,
when the compiler "sees" and checks a generic' source, it couldn't make any
diagnostics if it hadn't an idea on what the instanciation type will look
like.
- Many people claims that C++ templates are hard to use because the
"constraints" in the code (the instanciation type must provide such and such
method for example) are not clearly expressed, but are messed up inside the
template implementation. This make is very difficult to use templates as a
"black box" library because very often the library user must dive deep
inside the library source details to understand the requirements on the
instanciation types he provides to the library.
This is also what make the C++ template compiler error messages notoriously
very hard to read and understand.
Btw, there are several proposals for the next C++ standard (C++0x) to add
the notion of "Concepts", which are very similar to C# generics constraints.
See
http://www.cs.rice.edu/~jgs3847/pubs...epts_cpp0x.pdf
for an example of what it may looks like.
Arnaud
MVP - VC