c++ - GCC模板问题

标签 c++ templates gcc

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

第 29 行:错误:应为 `;'在“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 是对的,const_iterator 是一个类型,并且模板依赖于模板运算符<<,你需要告诉编译器它是一个类型而不是变量:

typename std::list<T>::const_iterator

关于c++ - GCC模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/389797/

相关文章:

multithreading - 编译时-pthread和-lpthread之间的区别

c++ - 如何强制 gcc 从库中链接未引用的静态 C++ 对象

c++ - 如何对卡诺图中的单元格进行分类

c++ - C++ 中的模板特化

c++ - 模板特化 GCC 的语法错误,但不是 MSVC

c++ - fatal error : iostream: No such file or directory in compiling C program using GCC

c++ - 关于函数对象的这段是什么

c++ - 找到OpenCV.cmakeConfig.cmake

C++11 可变模板函数存储

c++ - 如何在 C++ 中将多个不同类型的变量打印到控制台