How to declare and define a generic template flip_map function?

13 hours ago 4
ARTICLE AD BOX

I have the following in a header file:

template <typename A, typename B> pair<B, A> flip_pair(const pair<A, B> &); template <typename A, typename B, typename Cmp = less<iter_value_t<B>>> multimap<B, A, Cmp> flip_map(const map<A, B> &);

The intellisense shows the following error over `typename Cmp`:

no type named ‘value_type’ in ‘using std::__detail::__iter_traits_impl<long unsigned int, std::indirectly_readable_traits<long unsigned int> >::type = struct std::indirectly_readable_traits<long unsigned int>’ {aka ‘struct std::indirectly_readable_traits<long unsigned int>’}gcc

The following code in a .cpp:

template <typename A, typename B> pair<B, A> flip_pair(const pair<A, B> &p) { return pair<B, A>(p.second, p.first); } template <typename A, typename B, typename Cmp> multimap<B, A, Cmp> flip_map(const map<A, B> &src) { multimap<B, A, Cmp> dst; ranges::transform(src, inserter(dst, dst.begin()), flip_pair<A, B>); return dst; }

hits the following build error:

MyApp.cpp:2345:57: error: no matching function for call to ‘flip_map(std::map<std::__cxx11::basic_string<char>, long unsigned int>&)’ 2345 | multimap<size_t, string> myFlippedMap = flip_map(myKeyCount); | ~~~~~~~~^~~~~~~~~~~~ MyApp.cpp:2345:57: note: there is 1 candidate MyApp.h:147:21: note: candidate 1: ‘template<class A, class B, class Cmp> std::multimap<B, A, Cmp> flip_map(const std::map<K, V>&)’ 147 | multimap<B, A, Cmp> flip_map(const map<A, B> &); | ^~~~~~~~ MyApp.h:147:21: note: template argument deduction/substitution failed: MyApp.h:146:35: error: no type named ‘value_type’ in ‘using std::__detail::__iter_traits_impl<long unsigned int, std::indirectly_readable_traits<long unsigned int> >::type = struct std::indirectly_readable_traits<long unsigned int>’ {aka ‘struct std::indirectly_readable_traits<long unsigned int>’} 146 | template <typename A, typename B, typename Cmp = less<iter_value_t<B>>> | ^~~~~~~~
Read Entire Article