Reputation: 3473
I'm in a project where we want globally defined constant variables.
At the moment we have a class like
class Settings
{
public:
static constexpr unsigned int CONSTANT_ONE{1};
...
}
The problem is some of these constants we would rather have be able to be set at program start (as the title states, the user should be able to do this) instead of being predefined in code.
Is there a nice way to do this, and still have the variables constant?
Thankful for input, cheers!
Upvotes: 2
Views: 121
Reputation: 393
I did something similar but not quite sure it would serve your need though.
I declare the following string in class private section in header:
static const char mod_name[32];
I then instantiate it in source like following:
const char CLASS_NAME::mod_name[32] = "SOME STRING";
Maybe start from this and see how you can pass the value in?
Also, as a private const member, you can instantiate during instance construction which give you a way of passing in such constant values.
Upvotes: 0
Reputation: 7473
You can place constants at private
section of class Settings
, make static getters for them and write static function Initialize
:
class Settings
{
public:
static bool Initialize();
static unsigned int CONSTANT_ONE();
...
private:
static unsigned int constantOne;
...
};
...
bool Settings::Initialize()
{
static bool isInitialized = false;
if (isInitialized)
{
// error
return false;
}
else
{
isInitialized = true;
}
constantOne = 1;
...
return true;
}
unsigned int Settings::CONSTANT_ONE()
{
return constantOne;
}
...
You can also define macro to create getters automatically:
#define CONSTANT_NAME(Name) my_##Name
#define DECLARE_CONSTANT(Type, Name) \
public: \
static Type Name(); \
private: \
static Type CONSTANT_NAME(Name);
#define DEFINE_CONSTANT(Type, Name) \
Type Settings::Name() \
{ \
return CONSTANT_NAME(Name); \
} \
Type Settings::CONSTANT_NAME(Name);
Example of using:
class Settings
{
...
DECLARE_CONSTANT(unsigned int, CONSTANT_ONE)
...
};
...
DEFINE_CONSTANT(unsigned int, CONSTANT_ONE)
Upvotes: 3