简体   繁体   English

C ++任何具有特定值类型的迭代器?

[英]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 ). 现在问题是我知道该容器的value_type (而f()仅对该特定的value_type有意义)。 Is there a way to restrict iter_type to have a particular value_type ? 有没有办法将iter_type限制为具有特定的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. 我可能继承自std::iterator ,但f()只是一小段代码,不值得专用类。

You can get the value_type of the iterator via std::iterator_traits , and then check it at the compile time, eg 您可以通过std :: iterator_traits获取迭代器的value_type ,然后在编译时检查它,例如

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 : 你可以使用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 . 这将使限制成为函数签名的一部分,这意味着您可以使用具有相同名称和参数的另一个函数模板,只要它对此特定value_type禁用即可。

Edit : Using iterator_traits to make this more robust. 编辑 :使用iterator_traits使其更加健壮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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