Deduce type of template type in C++

后端 未结 2 2100
庸人自扰
庸人自扰 2021-02-12 20:20

When writing generic functions for \"iterator\" ranges I usually do:

template  auto func(Iter &first, Iter &last)
{
    using IterTy         


        
相关标签:
2条回答
  • 2021-02-12 20:45

    The second is the most idiomatic one.

    • The first does not work with proxies (std::vector < bool > )
    • The third does not work with pointers.
    0 讨论(0)
  • 2021-02-12 20:49

    None of these are quite idiomatic; you should be passing iterators by value, not by reference. Here's the signature for for_each in gcc 4.9:

    template<typename _InputIterator, typename _Function>
    _Function
    for_each(_InputIterator __first, _InputIterator __last, _Function __f)
    

    As you can see, it's passed by value. Your functions will not work in the idiomatic usage:

    func(v.begin(), v.end()); // error, binding non-const ref to rvalue!
    

    Also, going through iterator_traits is more than just idiomatic, it's basically required. Insofar as the STL is concerned, such typedefs are defined solely through iterator_traits: http://en.cppreference.com/w/cpp/concept/ForwardIterator. iterator_traits provides reasonable defaults for the generic case, but it can be specialized (as it is for pointers) to do different things. Not going through iterator_traits basically means someone could write a compliant iterator that worked with the STL but not your code.

    0 讨论(0)
提交回复
热议问题