Jean-Luc Nacif Coelho
Jean-Luc Nacif Coelho

Reputation: 1022

C++ Is there a way to get template types?

I have a map visitor that's templated like this

template <class Map> class MyVisitor : public MyMapVisitor<Map>;

With Map being necessarily an std::map

And I want to have a method in it that I would like to create a list of all the members stored in my map as such:

std::vector <Map::*second_template_argument*> toList ();

Is there a way to do this? Because I'm not allowed to change the MyMapVisitor superclass but I can change the MyVisitor subclass.

Upvotes: 0

Views: 126

Answers (4)

dlf
dlf

Reputation: 9373

For the more general case, if the class isn't kind of enough to provide typedefs for its template types, you can use decltype (if you have C++11). For your map example, you could do this:

std::map<int, double> myMap;

typedef decltype(myMap.begin()->second) valueType; // double
std::vector<valueType> myVector;

Note that myMap.begin() is not actually called by this code; the decltype expression simply evaluates to whatever type myMap.begin()->second would have returned (which is double in this case).

Obviously it's nicer to rely on the typedefs when you have them!

Upvotes: 1

IdeaHat
IdeaHat

Reputation: 7881

There are a few ways. The first is to make the implmenetation a specialization.

template <class MapType> class MyVisitor;

template <class T, class J>
class MyVisitor<Map<T,J>>: public MyMapVisitor<Map<T,J>>
{
  std::vector<J> toList();
}

I personally don't like this one, but sometimes it is all you've got.

The second is to expose the type via a public typedef (the way vector does):

template <typename T, typename J>
struct MyMap
{
  typedef T sometype;
  typedef J someothertype;
}

And then

std::vector<Map::someothertype> toList();

Upvotes: 0

cppguy
cppguy

Reputation: 3713

No. What you're describing is the ability to pass not a type but a member of the class. That can be passed at run time but there's no way to pass the name of a member as a template parameter.

Upvotes: 0

user2249683
user2249683

Reputation:

For a std::map you have three options:

  • std::map::value_type, which is a key/value pair
  • std::map::key_type for the key
  • std::map::mapped_type for the mapped value.

Upvotes: 8

Related Questions