Given the following:
template
class A
{
public:
static const unsigned int ID = ?;
};
I want ID to generate a unique c
Here is a possible solution mostly based on templates:
#include
#include
#include
template
struct wrapper {
using type = T;
constexpr wrapper(std::size_t N): N{N} {}
const std::size_t N;
};
template
struct identifier: wrapper... {
template
constexpr identifier(std::index_sequence): wrapper{I}... {}
template
constexpr std::size_t get() const { return wrapper::N; }
};
template
constexpr identifier ID = identifier{std::make_index_sequence{}};
// ---
struct A {};
struct B {};
constexpr auto id = ID;
int main() {
switch(id.get()) {
case id.get():
std::cout << "A" << std::endl;
break;
case id.get():
std::cout << "B" << std::endl;
break;
}
}
Note that this requires C++14.
All you have to do to associate sequential ids to a list of types is to provide that list to a template variable as in the example above:
constexpr auto id = ID;
From that point on, you can get the given id for the given type by means of the get method:
id.get()
And that's all. You can use it in a switch statement as requested and as shown in the example code.
Note that, as long as types are appended to the list of classes to which associate a numeric id, identifiers are the same after each compilation and during each execution.
If you want to remove a type from the list, you can still use fake types as placeholders, as an example:
template struct noLonger { };
constexpr auto id = ID, B>;
This will ensure that A has no longer an associated id and the one given to B won't change.
If you won't to definitely delete A, you can use something like:
constexpr auto id = ID, B>;
Or whatever.