What's the best way of defining a simple constant value in C++11, such that there is no runtime penalty? For example: (not valid code)
// Not ideal, no type, easy to put in wrong spot and get weird errors
#define VALUE 123
// Ok, but integers only, and is it int, long, uint64_t or what?
enum {
Value = 123
};
// Could be perfect, but does the variable take up memory at runtime?
constexpr unsigned int Value = 123;
class MyClass {
// What about a constant that is only used within a class, so
// as not to pollute the parent namespace? Does this take up
// memory every time the class is instantiated? Does 'static'
// change anything?
constexpr unsigned int Value = 123;
// What about a non-integer constant?
constexpr const char* purpose = "example";
std::string x;
std::string metadata() { return this->x + (";purpose=" purpose); }
// Here, the compiled code should only have one string
// ";purpose=example" in it, and "example" on its own should not
// be needed.
};
Edit
Since I've been told this is a useless question because there's no background behind it, here's the background.
I am defining some flags, so that I can do something like this:
if (value & Opaque) { /* do something */ }
The value of Opaque
won't change at runtime, so as it is only needed at compile time it seems silly to have it end up in my compiled code. The values are also used inside a loop that runs multiple times for each pixel in an image, so I want to avoid runtime lookups that will slow it down (e.g. a memory access to retrieve the value of the constant at runtime.) This isn't premature optimisation, as the algorithm currently takes about one second to process an image, and I regularly have over 100 images to process, so I want it to be as fast as possible.
Since people are saying this is trivial and not to worry about it, I'm guessing #define
is as close as you can get to a literal value, so maybe that's the best option to avoid "overthinking" the problem? I guess general consensus is you just hope nobody ever needs to use the word Opaque
or the other constants you want to use?