I have two c++ programs that need to have a map type -> int
that is known at compile time and equal between the two programs. Furthermore, I'd like to automatically make sure at compile time that the map is one-to-one. How would you solve that? (c++0x-extensions are allowed). The first part is easy: Share a
template < typename T > struct map;
template <> struct map <...> { enum { val = ...; }; };
between the programs. (The second part means that I don't want to accidently define the same val
for two different types somewhere in my programs.)
One way to ensure uniqe ids is to abuse friend function definitions
template<int N>
struct marker_id {
static int const value = N;
};
template<typename T>
struct marker_type { typedef T type; };
template<typename T, int N>
struct register_id : marker_id<N>, marker_type<T> {
private:
friend marker_type<T> marked_id(marker_id<N>) {
return marker_type<T>();
}
};
template<typename T>
struct map;
template<>
struct map<int> : register_id<int, 0> { };
// The following results in the following GCC error
// x.cpp: In instantiation of 'register_id<float, 0>':
// x.cpp:26:43: instantiated from here
// x.cpp:14:29: error: new declaration 'marker_type<float> marked_id(marker_id<0>)'
// x.cpp:14:29: error: ambiguates old declaration 'marker_type<int> marked_id(marker_id<0>)'
//
//// template<>
//// struct map<float> : register_id<float, 0> { };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With