[英]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
}
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.