Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting key_type from value_type

Tags:

c++

std

templates

I have a class X that operates on std containers. A function that takes a value_type as argument must call a function that takes a key_type as argument. How do I do that? I seems so basic.

template<typename C>
class X
{
  void foo(typename C::value_type vt)
  {
    bar(vt.first); // this works for C = std::map
    bar(vt); // this works for C = std::set
  }
  void bar(typename C::key_type kt)
  {
     ...
  }
};
like image 236
XPlatformer Avatar asked Feb 24 '26 10:02

XPlatformer


1 Answers

Add a (private) bar overload that is a function template and takes a T::value_type as argument.

template<typename C>
class X
{
public:
  void foo(typename C::value_type vt)
  {
    bar(vt);
  }

  void bar(typename C::key_type kt)
  {}

private:
  template<typename T = C>
  void bar(typename T::value_type kt)
  {
     bar(kt.first);
  }
};

When C is an std::map, the call to bar within foo will resolve to the member function template, and it'll then call other bar with the correct argument.

When C is an std::set, the call to bar will match both the bar overloads, but since one is a member function template, and the other isn't, the latter will be considered a better match.

Live demo

like image 84
Praetorian Avatar answered Feb 27 '26 00:02

Praetorian