Home > Mobile >  How to get const_iterator when the T is 'const std::map',?
How to get const_iterator when the T is 'const std::map',?

Time:09-29

I have the following struct:

template<typename T>
struct Foo 
{
  typename T::iterator iter;
};

The expected type:

  • iter is a std::map<K, V>::iterator when T is deduced as std::map<K, V>.

  • iter is a std::map<K, V>::const_iterator when T is deduced as const std::map<K, V>

But my code always get a std::map<K, V>::iterator.

How to achieve the expected implementation?

CodePudding user response:

You can provide a std::conditional type:

#include <type_traits>  // std::conditional_t

template<typename T>
struct Foo {
  using iter = std::conditional_t<std::is_const_v<T>
               , typename T::const_iterator
               , typename T::iterator>;
};
  • Related