【发布时间】:2012-12-26 04:05:33
【问题描述】:
ProcessIndex( int index );
template< typename Iterator >
void ProcessIndexes( Iterator start, Iterator end )
{
while( start!=end )
{
ProcessIndex(*start++);
}
}
我怎样才能强制这个函数只能用一个特定的、固定的迭代器值类型来调用,例如int(但任何容器类型)?在这种情况下,ProcessIndex() 将 int 作为输入,因此,非原始类型的编译失败并生成警告,例如float。但是,我希望声明强制执行 int,这样除了 int 之外的所有编译都失败。
尽管努力了,但在这里或其他地方还没有找到“解决方案”,这是否微不足道(?)。
【问题讨论】:
-
static_assert(std::is_same<typename std::iterator_traits<Iterator>::value_type, int>::value, "ProcessIndexes: Iterators must point to int.");-- 不知道你为什么想要那个,但是嘿...... -
你确定模板函数和迭代器在这种情况下是合适的吗?为什么不传递
int的向量或int的数组? -
Xeo 有正确的方法,但我会跳过
iterator_traits,只测试decltype(*start)。 -
Re ahenderson:因为函数(实际上是一个类方法)也应该接受 std::list、std::set、std::map、std::you_name_it :-) 我会喜欢的传递具有固定类型的任意容器,但了解到它通常使用迭代器完成,这具有排除 c 样式类型数组的额外好处。
-
@Ben:我不会,因为
decltype(*start)可能是int&或int const&。 :)
标签: c++ templates stl function-templates