I have some code that I need to run for separate cases. I would have to switch mostly some enums and statics for those cases. So, let's say I have enums
enum class City { NY, LA, W_DC, ... }
City capital = City::W_DC
and for the other case
enum class City { LDN, BMH, EDB, ... }
City capital = City::LDN
Assuming I have a lot of those enums, what is the best way to reuse most of the code and switch between those configuration. To be clear, this is not meant to happen during runtime, the program is supposed to compile for one case and be oblivious about anything else.
EDIT: following StackOverflowUser to use macros
would it be a good approach to store the different enum configs in different namespaces and then do
#IFDEF USE_NAMESPACE_A
using namespace namespace_a
#ELSE
using namespace namespace_a
#ENDIF
Creating macros and using #ifdef MACRONAME is the best way to check things before run time, in my opinion.
You can also create constexpr variables and use ifs to evaluate those variables' values. Since the variables are constexpr, the compiler would most likely optimize them away.
One option is to create separate source files, each containing the enum you want. You then make different compile targets that compile the relevant file as part of the build.
Another option is to use the #ifdef...#else preprocessor macros as stated previously, but you'll likely have different compile targets to define the macro that includes the correct file. Rather than set it up so you have to change code AND change the build, just put it in the build.
But, honestly, enums are probably not the best way to do what you're wanting to do. A lookup from a file/database/or some other datasource at runtime would likely be a more maintainable approach. It requires a bit more work obviously, but if this is something to maintain long-term you'll thank yourself later.
Related
I am currently working on a general-purpose C++ library.
Well, I like using real-word function names and actually my project has a consistent function naming system. The functions (or methods) start with a verb if they do not return bool (in this case they start with is_)
The problem is this can be somewhat problematic for some programmers. Consider this function:
#include "something.h"
int calculate_geometric_mean(int* values)
{
//insert code here
}
I think such functions seem to be formal, so I name my functions so.
However I designed a simple Macro system for the user to switch function names.
#define SHORT_NAMES
#include "something.h"
#ifdef SHORT_NAMES
int calc_geometric_mean(int* values)
#else
int calculate_geometric_mean(int* values)
#endif
{
//some code
}
Is this wiser than using alias (since each alias of function will be allocated in the memory), or is this solution a pure evil?
FWIW, I don't think this dual-naming system adds a lot of value. It does, however, has the potential for causing a lot of confusion (to put it mildly).
In any case, if you are convinced is a great idea, I would implement it through inline functions rather than macros.
// something.h
int calculate_geometric_mean(int* values); // defined in the .cpp file
inline int calc_geo_mean(int* values) {
return calculate_geometric_mean(values);
}
What symbols will be exported to the object file/library? What if you attempt to use the other version? Will you distribute two binaries with their own symbols?
So - no, bad idea.
Usually, the purpose behind a naming system is to aid the readability and understanding of the code.
Now, you effectively have 2 systems, each of which has a rationale. You're already forcing the reader/maintainer to keep two approaches to naming in mind, which dilutes the end goal of readability. Never mind the ugly #defines that end up polluting your code base.
I'd say choose one system and stick to it, because consistency is the key. I wouldn't say this solution is pure evil per se - I would say that this is not a solution to begin with.
I'm using a technique similar to this to associated information and/or actions with enumerators. It works pretty well, but there's a minor issue of needing to effectively list every constant twice, once in the header file in the enum declaration, and once in the source file in the lookup table. I'm wondering if there's any good way, probably with preprocessor trickery (Boost.Preprocessor is acceptable), to "automate" it so that I can enter the enum constants and associated values etc in just one place and have all the necessary stuff (perhaps even the lookup struct itself) get generated.
I'd prefer a method that maintains vaguely enum-style syntax, if possible; eg, something like DECLARE_ENUM(...) {E_CONST(...), E_CONST(...)};. I've seen some sites mentioning the idea of double-including the header file in order to achieve this, i.e. something like this:
#include "my_enum.hpp"
#undef ENUM_HPP // undefine the include guard
#undef E_CONST
#define E_CONST(...) /* something here */
#include "my_enum.hpp"
...but I'm not sure how useful that technique would be here. In particular, there is more than just the enum defined in the header; the lookup table struct is also there, along with a couple of other related enums and supporting functions.
I'm already using a macro to define the elements in the lookup table (it uses C99 initializers so that the entries will always be in the right place even if I rearrange the order of the enum constants).
A solution that can be applied to multiple enums would be nice as well.
I'm using clang (Apple-3.1) for this and am not particularly worried about portability.
I had an attempt somewhere that I threw away... I can't remember why it didn't work. Maybe I can find it in Time Machine...
Using the preprocessor trick, you would define your enums in a different file (say, enum_foo.def). It would be an unguarded file that gets #included.
ENUM_FOO_DEF(ALPHA, 9, 2)
ENUM_FOO_DEF(BETA, 10, 3)
ENUM_FOO_DEF(GAMMA, 12, 7)
ENUM_FOO_DEF(DELTA, 13, 11)
//...
Then in your source file, you would do something along the lines of:
enum FooEnum {
#define ENUM_FOO_DEF(X,Y,Z) FOO_E_ ## X,
#include "enum_foo.def"
#undef ENUM_FOO_DEF
FOO_E_MAX
};
And you can do something similar to populate your table of enum attributes.
Look at my gist for string enums https://gist.github.com/3058317
Maybe you should write your own code generator which takes some data file with the names and associated values and generates the header file and data table, probably as a standalone C module.
This program will be trivial to write, but immensely powerful for your use.
After browsing some old code, I noticed that some classes are defined in this manner:
MIDL_INTERFACE("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
Classname: public IUnknown {
/* classmembers ... */
};
However, the macro MIDL_INTERFACE is defined as:
#define MIDL_INTERFACE(x) struct
in C:/MinGW/include/rpcndr.h (somewhere around line 17). The macro itself is rather obviously entirely pointless, so what's the true purpose of this macro?
In the Windows SDK version that macro expands to
struct __declspec(uuid(x)) __declspec(novtable)
The first one allows use of the __uuidof keyword which is a nice way to get the guid of an interface from the typename. The second one suppresses the generation of the v-table, one that is never used for an interface. A space optimization.
This is because MinGW does not support COM (or rather, supports it extremely poorly). MIDL_INTERFACE is used when defining a COM component, and it is generated by the IDL compiler, which generates COM type libraries and class definitions for you.
On MSVC, this macro typically expands to more complicated initialization and annotations to expose the given C++ class to COM.
If I had to guess, it's for one of two use cases:
It's possible that there's an external tool that parses the files looking for declarations like these. The idea is that by having the macro evaluate to something harmless, the code itself compiles just fine, but the external tool can still look at the source code and extract information out of it.
Another option might be that the code uses something like the X Macro Trick to selectively redefine what this preprocessor directive means so that some other piece of the code can interpret the data in some other way. Depending on where the #define is this may or may not be possible, but it seems reasonable that this might be the use case. This is essentially a special-case of the first option.
I am currently writing various optimizations for some code. Each of theses optimizations has a big impact on the code efficiency (hopefully) but also on the source code. However I want to keep the possibility to enable and disable any of them for benchmarking purpose.
I traditionally use the #ifdef OPTIM_X_ENABLE/#else/#endif method, but the code quickly become too hard to maintain.
One can also create SCM branches for each optimizations. It's much better for code readability until you want to enable or disable more than a single optimization.
Is there any other and hopefully better way work with optimizations ?
EDIT :
Some optimizations cannot work simultaneously. I may need to disable an old optimization to bench a new one and see which one I should keep.
I would create a branch for an optimization, benchmark it until you know it has a significant improvement, and then simply merge it back to trunk. I wouldn't bother with the #ifdefs once it's back on trunk; why would you need to disable it once you know it's good? You always have the repository history if you want to be able to rollback a particular change.
There are so many ways of choosing which part of your code that will execute. Conditional inclusion using the preprocessor is usually the hardest to maintain, in my experience. So try to minimize that, if you can. You can separate the functionality (optimized, unoptimized) in different functions. Then call the functions conditionally depending on a flag. Or you can create an inheritance hierarchy and use virtual dispatch. Of course it depends on your particular situation. Perhaps if you could describe it in more detail you would get better answers.
However, here's a simple method that might work for you: Create two sets of functions (or classes, whichever paradigm you are using). Separate the functions into different namespaces, one for optimized code and one for readable code. Then simply choose which set to use by conditionally using them. Something like this:
#include <iostream>
#include "optimized.h"
#include "readable.h"
#define USE_OPTIMIZED
#if defined(USE_OPTIMIZED)
using namespace optimized;
#else
using namespace readable;
#endif
int main()
{
f();
}
Then in optimized.h:
namespace optimized
{
void f() { std::cout << "optimized selected" << std::endl; }
}
and in readable.h:
namespace readable
{
void f() { std::cout << "readable selected" << std::endl; }
}
This method does unfortunately need to use the preprocessor, but the usage is minimal. Of course you can improve this by introducing a wrapper header:
wrapper.h:
#include "optimized.h"
#include "readable.h"
#define USE_OPTIMIZED
#if defined(USE_OPTIMIZED)
using namespace optimized;
#else
using namespace readable;
#endif
Now simply include this header and further minimize the potential preprocessor usage. Btw, the usual separation of header/cpp should still be done.
Good luck!
I would work at class level (or file level for C) and embed all the various versions in the same working software (no #ifdef) and choose one implementation or the other at runtime through some configuration file or command line options.
It should be quite easy as optimizations should not change anything at internal API level.
Another way if you'are using C++ can be to instantiate templates to avoid duplicating high level code or selecting a branch at run-time (even if this is often an acceptable option, some switches here and there are often not such a big issue).
In the end various optimized backend could eventually be turned to libraries.
Unit Tests should be able to work without modifying them with every variant of implementation.
My rationale is that embedding every variant mostly change software size, and it's very rarely a problem. This approach also has other benefits : you can take care easily of changing environment. An optimization for some OS or some hardware may not be one on another. In many cases it will even be easy to choose the best version at runtime.
You may have two (three/more) version of function you optimise with names like:
function
function_optimized
which have identical arguments and return same results.
Then you may #define selector in som header like:
#if OPTIM_X_ENABLE
#define OPT(f) f##_optimized
#else
#define OPT(f) f
#endif
Then call functions having optimized variants as OPT(function)(argument, argument...). This method is not so aestetic but it does so.
You may go further and use re#define names for all your optimized functions:
#if OPTIM_X_ENABLE
#define foo foo_optimized
#define bar bar_optimized
...
#endif
And leave caller code as is. Preprocessor does function substitution for you. I like it most, because it works transparently while per-function (and also per datatype and per variable) grained which is enough in most cases for me.
More exotic method is to make separate .c file for non-optimized and optimized code and compile only one of them. They may have same names but with different paths, so switching can be made by change single option in command line.
I'm confused. Why don't you just find out where each performance problem is, fix it, and continue. Here's an example.
Simple question, how do I shorten a call/name without using defines.
For example, I have a singleton that I have to call that is within a namespace (I cannot use using namespace blabla because it is not allowed) like so:
MyFW::GameRoot::Instance()->DoSomething();
Now I can assign that to a variable, which works somewhat if I am using it multiple times within the same class/function, but using it in many classes/functions it becomes cumbersome. I decided to use #define for it:
#define MyFW::GameRoot::Instance() ROOT //defined in GameRoot.h
ROOT->DoSomething(); //Used where-ever GameRoot.h is included
Much better, and I really like it especially because now wherever I see ROOT (color coded through V-Assist) I know what it is immediately... unless I have a breakpoint there and I need Visual Studio to resolve ROOT to show up in the watch window (or even hover over it to quickly pull up the object in debug), which it cannot do.
Is there any other option? What do you guys do to shorten names? Simply use local/member pointers to store the instance?
Thanks!
You can't use using namespace ..., but can you use
namespace root=MyFW::GameRoot;
Then you can type
root::Instance()->DoSomething();
Defining a namespace like that is better than a #define. (I.e it can't get munged up somewhere else by mistake. The compiler knows what you are trying to do.)
Use local references:
MyFW::GameRoot& ROOT = *MyFW::GameRoot::Instance();
Do not use defines.
If you want to ease access across multiple functions, just use a helper function:
namespace {
MyFW::GameRoot* root() { return MyFW::GameRoot::Instance(); }
}
// ...
root()->DoSomething();
Two characters more, but it with comes type-safety included.
The good way to do this (but never in a header) is
using MyFW::GameRoot;
GameRoot::Instance()->DoSomething;
This is a using declaration and is different from a using directive, which is what you mentioned above.