Wednesday, February 28, 2007

some nagging c++ questions

C++ always has some tricks in there that you just don't know about. Here are a couple of features/issues that I've run into. Am sure this list is pretty huge but lets start with three of them and my explanations for the same.

a) using "using namespace" in your header files

I was once asked why I go ahead and take the trouble to do a std::string in my header files instead of just including the "using namespace std" statement and moving along. There are a variety of reasons why the former is considered to be a good practice. Some of those are written in Herb Sutter's More Exceptional C++ book and many newgroups have their own threads on this issue (see namespace pollution).

For me the main reason was because of the namespace pollution caused when I have some headers with the "using" statement and some without and then being included in a particular sequence in a third header file. This as I remember caused some collisions. Other than that it also causes problems when you go ahead and include all these headers in your own namespace, thereby also including the "using" statement into your namespace, more problems.

b) the need to have template class functions as inline

Template classes are essentially compiled on demand. Once the compiler seems a template instantiation it goes back to where the declaration was seen and generates the type specific code of the template class immediately. Now while doing so it needs to generate the entire object code for the class. If we go ahead and sperate our template class into a .h declaration and .cpp definitions files then the compiler is left with incomplete information about what needs to be generated for this class. This is the reason why most compilers will cribb here. But this is a compiler issue rather than the C++ standard itself.

c) template functions in tempate classes

yes it is possible to do that. you just need to be a lil carefull thats all.

template < class x >
class tclass
x var;
tempate < typename y >
void func(y);

template < class x >
template < typename y >
void func( y fvar )
{ ... }

No comments: