【问题标题】:How to pass normal param as well as template param in a template function in C++?如何在 C++ 的模板函数中传递普通参数和模板参数?
【发布时间】:2011-10-03 04:14:00
【问题描述】:

我在名为 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:在函数“void myNamespace::getRandomItems(NaturalNumber, setX&, setX&) [with setX = std::set<:basic_string> >, NaturalNumber = long unsigned int]”中: 合成图.C:87:55: 从这里实例化 generic.h:74:32: 错误: 'it = index.std::set::begin [with _Key = long unsigned int, _Compare = std::less 中的 'operator=' 不匹配, _Alloc = std::allocator, std::set<_key _compare _alloc>::iterator = std::_Rb_tree_const_iterator]()' /usr/include/c++/4.5/bits/stl_tree.h:224:5:注意:候选是:std::_Rb_tree_const_iterator<:basic_string> >& std::_Rb_tree_const_iterator<:basic_string> >::operator=(const std::_Rb_tree_const_iterator<:basic_string> >&) 合成图.C:87:55: 从这里实例化 generic.h:74:32: 错误:'it != index.std::set<_key _compare _alloc>::end [with _Key = long unsigned int, _Compare = std ::less, _Alloc = std::allocator, std::set<_key _compare _alloc>::iterator = std::_Rb_tree_const_iterator]()' /usr/include/c++/4.5/bits/stl_tree.h:291:7:注意:候选是:bool std::_Rb_tree_const_iterator<_tp>::operator!=(const std::_Rb_tree_const_iterator<_tp>::_Self&) const [with _Tp = std::basic_string, std::_Rb_tree_const_iterator<_tp>::_Self = std::_Rb_tree_const_iterator<:basic_string> >] generic.h:77:4:错误:无法在赋值中将“const std::basic_string”转换为“NaturalNumber”

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

【问题讨论】:

  • I have tried all combinations: 告诉我们你尝试了哪些组合

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


【解决方案1】:

setX 不是NaturalNumbers 的集合,因此当您说it = index.begin() 时,迭代器不兼容。您可以将 it 设为 set&lt;NaturalNumber&gt; 的迭代器,但我无法确定您在这里真正想要做什么。

我还注意到,在您的内部循环中,您没有进行任何检查以确保 sit 不会超出其集合的末尾。

【讨论】:

  • 感谢@mark-b 和@sehe。与此相关的另一个问题是:如何将模板数据类型的集合作为函数的参数传递,如下所示: template void func(set myset);但这显示了错误。我该怎么做?
【解决方案2】:

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

也许你的意思

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

而不是

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

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多