It is not possible to initialize global constants at main
. By the time your program reaches it, all globals must have already been initialized.
However, it is possible to write a class that contains a value and only allows you to set it once. The check will have to be done at runtime, however.
Something like this (std::optional
requires C++17, but you don't have to use it):
#include <optional>
template <typename T>
class LateConstant
{
public:
LateConstant() = default;
LateConstant(const LateConstant&) = delete;
LateConstant& operator=(const LateConstant&) = delete;
LateConstant& operator=(const T& x)
{
if (!v.has_value())
{
v = std::make_optional<T>(x);
}
else
{
std::terminate();
}
return *this;
}
bool has_value() const
{
return v.has_value();
}
const T& value() const
{
return v.value();
}
private:
std::optional<T> v;
};
With this, if you try to assign a value more than once, your program intentionally crashes. It's not a constant, but it may still be useful.
Now, to be honest, you'd better avoid globals anyway. I haven't used them in years, after I've been bitten several times. If you decide not to use globals, you can use constant locals instead or collect the data you need in a class and pass that around.
Another possibility is to use something like
int whatever(int i = 0)
{
static const int stored = i;
return stored;
}
If you try to set it more than once, it will just ignore the value, which could be a bad idea.