MetroWind
MetroWind

Reputation: 541

C++: generate template argument?

I run into the unfortunate situation that I need to write the following code:

std::map<type1_key, type1_value, type1_cmp> x;
std::map<type2_key, type2_value, type2_cmp> y;
std::map<type3_key, type3_value, type3_cmp> z;
// ...

These key/value/cmp types are predefined for me. Their type names all follow this _key, _value, and _cmp pattern (those are not templates). Is there a built-in way to simplify this into

map_type<type1> x;
// ...

or

map_type(type1) x; // some kind of macro??
// ...

Upvotes: 2

Views: 112

Answers (3)

user975989
user975989

Reputation: 2648

I suggest an approach that uses the type system more

template <std::size_t I>
struct kvc;

template <>
struct kvc<1> {
    using key = type1_key;
    using value = type1_value;
    using cmp = type1_cmp;
};
// Similar for the other types

template <std::size_t I>
using map_type = 
    std::map<typename kvc<I>::key, typename kvc<I>::value, typename kvc<I>::cmp>;

You can automate the creation of the specializations with a macro, but this way you have more fine tuned control of the key/value/cmp and you get (in my opinion) nicer errors.

Upvotes: 1

Jon Purdy
Jon Purdy

Reputation: 54971

I find the macro solution preferable, but here is a version that wraps the information in a traits structure, if you don’t want the macro to pollute the global scope:

#define make_traits(T) \
struct T##_traits { \
  typedef T##_key key; \
  typedef T##_value value; \
  typedef T##_cmp cmp; \
}

make_traits(type1);
make_traits(type2);
make_traits(type3);

#undef make_traits

template<typename T>
using map_type =
  std::map<typename T::key, typename T::value, typename T::cmp>;

map_type<type1_traits> x;

Upvotes: 4

P0W
P0W

Reputation: 47784

You can use following macro:

   #define map_type( x ) std::map<x##_key, x##_value, x##_cmp>

Then,

map_type(type1) x;

Upvotes: 5

Related Questions