forward_list: assign(_InputIterator __first, _InputIterator __last) / assign(size_type __n, const _Tp& __val)

前端 未结 2 1951
遇见更好的自我
遇见更好的自我 2021-01-24 18:51

I have implemented a subset of the forward_list and wanted to test the method assign(size_type __n, const _Tp& __val) but I get a compiler error be

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-24 19:18

    The assign overload that you want to be called takes an unsigned integral type as the first argument, but you're passing it two signed integers. If you change the call to

    l.assign(10U, 5);  // make the first argument unsigned
    

    the first assign overload is called. But clearly, this is not the right solution to your problem in general.

    You need to constrain the assign template so that it is only viable when the type of the arguments satisfy requirements for iterators. One way to do this is to inspect iterator_traits for the type involved. If the iterator_category satisfies the requirements of an InputIterator, then the function template can be used.

    template
    typename std::enable_if<
        std::is_base_of::iterator_category
                       >::value
             >::type
        assign(InputIterator first, InputIterator last)
    {
      printf("%s\n", __PRETTY_FUNCTION__);
    }
    

    Live demo

    Note that technically the above solution isn't guaranteed to work before C++17 (or whatever it'll be called) because iterator_traits isn't required to be SFINAE friendly until then, and it could result in a hard error instead of substitution failure. But chances are your implementation's iterator_traits is already SFINAE friendly, and you won't run into any issues.


    size_t isn't guaranteed to be included by , use one of the headers listed on the linked page.

    Don't use identifiers that begin with an underscore and are followed by an uppercase characters, those are reserved for the implementation.

提交回复
热议问题