假设我有一个函数模板来循环遍历某个容器的任何迭代器:
template<class iter_type>
void f(iter_type start, iter_type finish)
{
// loop from start to finish
}
现在问题是我知道那个容器的
value_type
(并且 f()
只对那个特定的 value_type
有意义)。有没有办法限制 iter_type
具有特定的 value_type
?我可能可以从
std::iterator
继承,但 f()
只是一小段代码,不值得专门的类。 最佳答案
您可以通过 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
关于C++ 任何具有特定值类型的迭代器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46801407/