简体   繁体   中英

C++ any iterator with a specific value type?

Suppose I have a function template to loop through any iterator of some container:

template<class iter_type>
void f(iter_type start, iter_type finish)
{
   // loop from start to finish
}

Now the thing is I know the value_type of that container (and f() only makes sense with that particular value_type ). Is there a way to restrict iter_type to have a particular value_type ?

I can probably inherit from std::iterator , but f() is just really a small piece of code that doesn't deserve a dedicated class.

You can get the value_type of the iterator via std::iterator_traits , and then check it at the compile time, eg

template<class iter_type>
void f(iter_type start, iter_type finish)
{
    static_assert(
      std::is_same<
        typename std::iterator_traits<iter_type>::value_type,
        specific_value_type>::value, 
      "The value_type must be specific_value_type.");

    // loop from start to finish
}

LIVE

You can use std::enable_if :

template<class iter_type>
auto f(iter_type start, iter_type finish)
 -> typename std::enable_if<std::is_same<
                            typename std::iterator_traits<iter_type>::value_type,
                            particular_value_type
                                        >::value, void>::type
{
   // loop from start to finish
}

This will make the restriction part of your function's signature, which means you can have another function template of the same name and arguments, as long as it is disabled for this particular value_type .

Edit : Using iterator_traits to make this more robust.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM