如何在C ++中的模板函数中传递普通参数和模板参数?

时间:2011-07-11 21:46:26

标签: c++ compiler-errors function-templates template-function

我在名为myNamespace的名称空间中有一个模板函数(如下所示):

template <typename setX>
void getRandomItems(NaturalNumber size, setX &random, setX &items)
{
    assert(size <= items.size());

    //set of randomly selected indices for items
    set<NaturalNumber> index;
    NaturalNumber r, i;

    while(index.size() < size)
    {
        r = unifRand(0,items.size()-1);
        index.insert(r);
    }

    typename setX::iterator it, sit = items.begin();
    for(i = 0, it = index.begin(); it != index.end(); it ++)
    {
        //find the r-th elt in index
        r = *it;
        for(; i < r; i ++)
            sit++;

        random.insert(*sit);
    }
}

然而,每当我调用此函数时,我都会收到这些错误:

generic.h: In function ‘void myNamespace::getRandomItems(NaturalNumber, setX&, setX&) [with setX = std::set<std::basic_string<char> >, NaturalNumber = long unsigned int]’:
synthetic-graph.C:87:55:   instantiated from here
generic.h:74:32: error: no match for ‘operator=’ in ‘it = index.std::set::begin [with _Key = long unsigned int, _Compare = std::less<long unsigned int>, _Alloc = std::allocator<long unsigned int>, std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<long unsigned int>]()’
/usr/include/c++/4.5/bits/stl_tree.h:224:5: note: candidate is: std::_Rb_tree_const_iterator<std::basic_string<char> >& std::_Rb_tree_const_iterator<std::basic_string<char> >::operator=(const std::_Rb_tree_const_iterator<std::basic_string<char> >&)
synthetic-graph.C:87:55:   instantiated from here
generic.h:74:32: error: no match for ‘operator!=’ in ‘it != index.std::set<_Key, _Compare, _Alloc>::end [with _Key = long unsigned int, _Compare = std::less<long unsigned int>, _Alloc = std::allocator<long unsigned int>, std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<long unsigned int>]()’
/usr/include/c++/4.5/bits/stl_tree.h:291:7: note: candidate is: bool std::_Rb_tree_const_iterator<_Tp>::operator!=(const std::_Rb_tree_const_iterator<_Tp>::_Self&) const [with _Tp = std::basic_string<char>, std::_Rb_tree_const_iterator<_Tp>::_Self = std::_Rb_tree_const_iterator<std::basic_string<char> >]
generic.h:77:4: error: cannot convert ‘const std::basic_string<char>’ to ‘NaturalNumber’ in assignment

我尝试了所有组合,但没有运气,请帮帮我!!!

2 个答案:

答案 0 :(得分:1)

setX不是NaturalNumber的集合,因此当您说it = index.begin()时,迭代器不兼容。您可能会使it成为set<NaturalNumber>的迭代器,我无法弄清楚您真正想要做的事情。

另外我注意到在你的内循环中你没有做任何检查以确保sit不会在它的集合结束时运行。

答案 1 :(得分:1)

您正在尝试分配不兼容的迭代器。

也许你的意思是

set<NaturalNumber>::iterator it;
typename setX::iterator sit = items.begin();

而不是

typename setX::iterator it, sit = items.begin();