This question more falls into the category of best practices, and clean/safe code for distribution.
I'm working on a math library in C++, for my portfolio, and to use during my last two semesters of College. I want this library to be very easy to use, and to minimize the possibilities of conflicts with pre existing code.
开发者_StackOverflow社区For readability I'm defining TEMP_T as a template for a class, at the top of each of my header files (math/matrix/vec/quaternion). It looks like the following:
#ifdef TEMP_T
#define UNDEF_TEMP_T TEMP_T // Used to reset any other definitions later.
#endif // TEMP_T
#define TEMP_T template<class T> // Used to make the code more readable.
Later on, at the end of the file, I reset the pre existing definition, if nessicary with the following:
#undef TEMP_T // Get rid of our definition.
#ifdef UNDEF_TEMP_T
#define TEMP_T UNDEF_TEMP_T // Reset the previous definition, if it existed.
#undef UNDEF_TEMP_T
#endif // UNDEF_TEMP_T
My question: Would this successfully create a define visible to the file, and the file alone? If so, is this how you would go about accomplishing such a thing? If not, would you be so kind as to give me some insight on your rational behind your ways of doing things?
IMO that is much less readable, falls into the class of pre-processor abuse and I would seriously recommend using the actual definition which will make your code more readable by others which is the point of readability.
In my eyes, you reduce readability this way. This would be the way to reduce the number of characters to be typed/read, but it increases the number of needed human-interpretations, too, which is a bad thing.
On top of that, if anyone has defined TEMP_T
in their own code, they would loose their definition by including your headers.
// my code.cpp
#define TEMP_T( var, vartype ) myclass<vartype> var( ##var );
#include <yourmathlib.h>
TEMP_T( anint, int ) // breaks. hard to find the real error.
As a consequence you may define a library-specific MYMATHLIB_TEMP_T
, which further decreases readability :)
You can just #include
the header file where you declared the template from your other header files.
And if you want to make sure that you don't include the same file twice from 2 different files, you can have
#ifndef MYMATHLIB_TEMP_T
#define MYMATHLIB_TEMP_T
// ... template ...
#endif
around the template header file.
you could just define TEMP_T in an header file and use that header in all your code, maybe you can try to test if your header is included by some macro. But this way of doing things increases the complexity to read your code.
Why not simply put your template class in a namespace? If you stick it in an namespace, you avoid all the nasty macro stuff. namespaces were explicitly designed to allow code units to be isolated form each other without naming conflicts.
精彩评论