本文介绍了GCC模板问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Visual Studio编译好这个代码,但gcc只允许它在没有Template运算符的情况下编译。使用模板运算符时,会出现以下错误:

第29行:错误:预期的;;itrValue之前

  class Test 
{
public:

Test&运算符<<<(const char * s){return * this;} //尚未实现
Test&运算符<<(size_t s){return * this;} //尚未实现

Test&运营商LT;< (const std :: list< const char *>& strList)
{
* this<< count =<< strList.size()<< (;

for(std :: list< const char *> :: const_iterator itrValue = strList.begin();
itrValue!= strList.end(); ++ itrValue)
{
* this<<<< * itrValue;
}

* this<<));

return * this;
}

模板< class T>
测试&运营商LT;< (const std :: list< T& listTemplate)
{
* this<< count =<< listTemplate.size()<< (;

//这是第28行,下一行是违规行
(std :: list< T> :: const_iterator itrValue = listTemplate.begin();
itrValue!= listTemplate.end(); ++ itrValue)
{
* this<<<<< * itrValue;
>

* this<<);

return * this;
}
};


解决方案

GCC是正确的,const_iterator是一个类型,依赖于模板运算符<<,你需要告诉编译器它是一个类型而不是变量:

  typename std: :list< T> :: const_iterator 


Visual Studio compiles this code fine, but gcc only lets it compile without the Template operator. With the Template operator it gives the following errors:

Line 29: error: expected `;' before "itrValue"

class Test
{
  public:

  Test& operator<<(const char* s) {return *this;} // not implemented yet
  Test& operator<<(size_t      s) {return *this;} // not implemented yet

  Test& operator<< (const std::list<const char*>& strList)
  {
    *this << "count=" << strList.size() << "(";

    for (std::list<const char*>::const_iterator itrValue = strList.begin();
         itrValue != strList.end(); ++itrValue)
    {
        *this << " " << *itrValue;
    }

    *this << ")";

    return *this;
  }

  template <class T>
  Test& operator<< (const std::list<T>& listTemplate)
  {
    *this << "count=" << listTemplate.size() << "(";

    // this is line 28, the next line is the offending line
    for (std::list<T>::const_iterator itrValue = listTemplate.begin();
         itrValue != listTemplate.end(); ++itrValue)
    {
        *this << " " << *itrValue;
    }

    *this << ")";

    return *this;
  }
};
解决方案

GCC is right, const_iterator is a type, and template dependant in the template operator<<, you need to tell the compiler it's a type and not a variable:

typename std::list<T>::const_iterator

这篇关于GCC模板问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:58