template< class T, int MAXN >
int BST< T, MAXN >::count( const T &x ) const
{
return find( x ) ? 1 : 0;
}- A generic type T is introduced into the scope of this member function.
- The template parameter MAXN is a compile time constant that is part of the type of the data structure.
- This is the count member function of the class BST, which is paramaterized on the types mentioned above.
- count does not modify any instance variables of BST.
- The parameter x is passed by constant reference.
- count's return type is int.
- The actual value returned is 1 if find(x) evaluates to true, and 0 if find(x) evaluates to false.
You learn to look for what you need to know when reading the code. Also, it's also worth noting that this code is most decidedly C++ only. C programmers may hate this code.
This really sucks for angle brackets though. Compare
vector<pair<int, string> > blah;
to
vector< pair< int, string > > blah;
I've been routinely programming in C++ for over a decade and this sort of required verbosity is what really rubs me the wrong way. This piece should really be:
int BST<T, >::count(T & x)
{
return find(x) ? 1 : 0;
}
When this is getting compiled, the template< class T, int MAXN > part can be unambiguously deduced from the context, so needing to type it is really a matter of helping a compiler do its job. MAXN is not used, so there's no need to drag it into the picture. Instead tell the compiler that BST can be specialized with more than one parameter by using trailing comma. The const-ness can and should be deduced automatically by looking at what find() is like, in a recursive fashion. If nothing in find() and the functions it calls modifies the x, then count() can accept const arguments and can be considered const itself.I mean, c'mon. My car can park itself, but my compiler can't understand parametrized types without hand-holding :)
I would argue that automatic inference of 'const' is a very bad idea because it defeats the whole purpose of having 'const' in the first place -- to catch bugs at compile time. If somebody modifies 'find()' in a way that makes it non-const, then your code will continue compiling without errors. However, if somebody relies on the fact that 'count()' is const, then that person would be royally screwed, and it will take weeks to find the bug.
Agreed. My code and a lot of C++ code I've seen uses uppercase for template parameters, but never for classes/structs or methods. (Actually, I generally follow the Java conventions for capitalization of class names, method/function names, constants etc, though I use underscores in local variables.)
What does find(x) do?
(Other than return something which evaluates in boolean context unless the template function is skipped for instantiation due to SFINAE and not modify x or *this unless a C-style or const_cast is used somewhere).
Stockholm '09 here.
Have the rules changed? Or are these libraries just for practice problems?