【问题标题】:How to get const_iterator when the T is 'const std::map',?当 T 为 'const std::map' 时如何获取 const_iterator?
【发布时间】:2021-09-28 08:48:12
【问题描述】:

我有以下结构:

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

预期类型:

  • iterstd::map&lt;K, V&gt;::iterator,而T 被推导出为std::map&lt;K, V&gt;

  • iterstd::map&lt;K, V&gt;::const_iterator,而T 推导出为const std::map&lt;K, V&gt;

但我的代码总是得到std::map&lt;K, V&gt;::iterator

如何实现预期的实现?

【问题讨论】:

    标签: c++ templates type-alias


    【解决方案1】:

    您可以提供std::conditional 类型:

    #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>;
    };
    

    【讨论】:

    • 你太有帮助了!!!!
    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 2019-10-30
    • 2020-12-21
    • 2019-10-20
    • 2021-06-02
    • 1970-01-01
    • 2019-12-02
    • 2021-08-08
    相关资源
    最近更新 更多