【问题标题】:Iterator of associative container is not dependent on Comparator template argument关联容器的迭代器不依赖于 Comparator 模板参数
【发布时间】:2015-06-29 23:26:32
【问题描述】:

编译器无法区分两种不同类型的迭代器。

在这里查看这两种类型。

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 编译。

错误:'template void LVOrderBookBin::erasePriceLevel(std::vector, std::allocator >>)' 不能重载

有解决办法吗?

【问题讨论】:

  • 请比“不起作用”更具体。
  • 我的意思是它不能编译。错误:'template void LVOrderBookBin::erasePriceLevel(std::vector<:_rb_tree_const_iterator>, std::allocator<:_rb_tree_const_iterator>> >)' 不能重载

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


【解决方案1】:

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

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()
{
    //...
}

【讨论】:

  • 是的,对不起,我超载了,不是专精。我也试过你提到的代码。但这些方法不起作用。由于 PriceBookBuyIter 和 PriceBookSellIter 与每个编译器的类型相同。
  • Works 对于您发布的示例,但您需要明确指定模板参数。
  • 您使用的是哪个编译器?我使用了 gcc 版本 4.4.7 20120313 和 VS2013 编译器。它曾经在 Vs2008 中为我工作。
  • 那个链接是 gcc 版本 4.9.2。
【解决方案2】:

标准库实现完全在他们的权利范围内,而且几乎是强制性的。您看到的效果被称为 SCARY 迭代器,这是一件好事。

您必须将迭代器包装在自定义结构中 - 使用您自己的自定义类型有效地标记它们才能以这种方式使用 OR。

【讨论】:

猜你喜欢
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 2021-10-16
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
相关资源
最近更新 更多