【问题标题】:C++ test for containers via SFINAE通过 SFINAE 对容器进行 C++ 测试
【发布时间】:2020-07-18 16:01:45
【问题描述】:

在 C++17 中,我试图通过检查 value_type (mapped_type) 的存在来检测容器(地图)。然而,虽然它似乎对unordered_set<int> 有效,但它对unordered_set<int*> 却失败了,我觉得这很奇怪。你能告诉我为什么以及如何正确地做到这一点吗?

  template<class N, class T = int>
  struct is_container { static const bool value = false; };
  template<class N>
  struct is_container<N, typename N::value_type> { static const bool value = true; };
  template<class N>
  static constexpr bool is_container_v = is_container<remove_reference_t<N>>::value;


int main()
{
  cout << is_container_v<unordered_set<int>&> << '\n';
  cout << is_container_v<unordered_set<int*>&> << '\n';
}

输出:

1
0

PS:我见过this question 会根据begin() 的存在进行过滤,但这无助于从set 中区分map

【问题讨论】:

    标签: c++ templates stl c++17 sfinae


    【解决方案1】:

    保持你的测试,它应该是

    template<class N, class Enabler = void>
    struct is_container { static const bool value = false; };
    
    template<class N>
    struct is_container<N, std::void_t<typename N::value_type>>
    { static const bool value = true; };
    
    template<class N>
    static constexpr bool is_container_v = is_container<remove_reference_t<N>>::value;
    

    和你的版本一样

    is_container_v&lt;unordered_set&lt;int*&gt;&amp;&gt;is_container&lt;unordered_set&lt;int*&gt;&gt;,默认为:is_container&lt;unordered_set&lt;int*&gt;, int&gt;

    而你专攻is_container&lt;unordered_set&lt;int*&gt;, int*&gt;...

    【讨论】:

    • 啊,谢谢你的解释,现在说得通了。我对专业有误解...
    猜你喜欢
    • 1970-01-01
    • 2013-05-02
    • 2020-03-31
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2017-09-21
    • 1970-01-01
    相关资源
    最近更新 更多