Reputation: 8717
I want to create an enum in C++11 in such a way that I can declare some constants value in a source code while declaring them in header file:
A.hpp
typedef enum class ABC: uint8_t
{
CAR,
DOG,
HOUSE
};
extern ABC ABCType;
A.cpp
#include "A.hpp"
ABCType = { CAR = 1, DOG = 2, HOUSE = 3 };
The reason to want this is the enum's initial values depend on some other library declarations and needs to be non-modifiable by users (just a coding style requirement for me). So, the user can use something like below:
#include "A.hpp"
int classA::method()
{
...
check(ABCType.HOUSE);
...
}
I tried this, but the VC++ IDE says "too many initializer values", why is that?
Upvotes: 0
Views: 209
Reputation: 11317
Your own requirement ain't a problem, this is the only way in C++. Once you define an enum class, the values into is are considered constants.
If you consider:
enum class Ext { SOME_VALUE};
And you want numeric values following it, I suggest writing:
enum class E : std:: underlying_t<Ext > {
CAT = static_cast<std:: underlying_t<Ext >>(Ext::SOME_VALUE)+1,
DOG
};
This way, CAT is defined as one higher than SOME_VALUE and DOG as one higher than CAT (always prev+1).
Upvotes: 0
Reputation: 117433
It's perhaps not exactly what you want, but could be useful.
scoped_opaque_enum.hpp
#pragma once
#include <cstdint>
enum class ABC : uint8_t;
extern ABC CAR, DOG, HOUSE;
scoped_opaque_enum.cpp
#include "scoped_opaque_enum.hpp"
ABC CAR = static_cast<ABC>(1), DOG = static_cast<ABC>(2), HOUSE = static_cast<ABC>(3);
use_soe.cpp
#include "scoped_opaque_enum.hpp"
#include <iostream>
int main() {
std::cout << static_cast<int>(CAR) << '\n';
}
Upvotes: 1
Reputation: 1072
Enum isn't a list of constants with various values (defined later). Enum defines values for items at declaration only. For your example, 'CAR' will have value '0' (and 'HOUSE' is 2), etc.
For you requeirements, you can create a class with some constants or functions which return need values. You make child classes with additional values, etc.
Upvotes: 0