关联容器的迭代器不依赖于Comparator模板参数

时间:2015-04-22 10:53:47

标签: c++ templates visual-studio-2013 stl iterator

编译器无法在两种不同类型的迭代器之间进行区分。

请在此处查看两种类型。

typedef std::set<int, std::greater<int> >             PriceBookBuy;
typedef std::set<int, std::less<int> >                PriceBookSell;

typedef PriceBookBuy::iterator PriceBookBuyIter;
typedef PriceBookSell::iterator PriceBookSellIter;

我想基于两个迭代器类型重载模板方法。

class LVOrderBookBin
{
    int a;
    int b;
    public:

   template<typename PriceBookBuy>
   void erasePriceLevel(std::vector<PriceBookBuyIter> remover) throw()
   {
            b++;
            remover.begin();
        }
        template<typename PriceBookSell>
        void erasePriceLevel(std::vector<PriceBookSellIter> remover) throw()
        {
            a++;
            remover.begin();
        }
};

典型用法:

int main()
{
    std::vector< PriceBookBuyIter> vecBuy(3);
    std::vector< PriceBookSellIter> vecSell(3);


    LVOrderBookBin lv;
    lv.erasePriceLevel<PriceBookBuy>(vecBuy);
    lv.erasePriceLevel<PriceBookSell>(vecBuy);
}

用于与Vs2008一起使用的相同代码,但不能使用VS2013进行编译。它也不能用gcc编译。

错误:'模板void LVOrderBookBin :: erasePriceLevel(std :: vector,std :: allocator&gt;&gt;)'无法重载

有解决方法吗?

2 个答案:

答案 0 :(得分:2)

标准库实现完全有权执行此操作,并且几乎是强制性的。你看到的效果被称为SCARY迭代器,这是一件好事。

您必须将迭代器包装在自定义结构中,并使用您自己的自定义类型对它们进行标记,以便以这种方式使用OR。

答案 1 :(得分:0)

这不是专门化模板的正确方法;你只是声明函数重载。你需要像这样专业化:

class LVOrderBookBin
{
public: 
    template<typename T>
    void erasePriceLevel(std::vector<typename T::iterator> remover) throw();
};

template<>
void LVOrderBookBin::erasePriceLevel<PriceBookBuy>
     (std::vector<PriceBookBuyIter> remover) throw()
{
    //...
}
template<>
void LVOrderBookBin::erasePriceLevel<PriceBookSell>
     (std::vector<PriceBookSellIter> remover) throw()
{
    //...
}