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)
{
...
}
};
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
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