自定义模板运算符上的错误C2676 <

问题描述 投票:0回答:1

我有封装2 loggerstd::ofstream类:

class logger
{           
  private:
    std::ofstream one;
    std::ofstream two;

  public:
    logger();
    ~logger();

    template<typename T> logger & operator<<(T);
};

logger::logger()
{
  // open streams
}

logger::logger()
{
  // close streams
}

template<typename T> logger & logger::operator<<(T log)
{
    this->one<<log;
    this->two<<log;
    return * this;
}

我使用它:

int main(int argc, char * argv[])
{
  debug::log << "Some strgins"; // works perfect.
  debug::log << std::endl; //  error C2676: binary '<<' : 'logger' does not define this operator or a conversion to a type acceptable to the predefined operator
  return 0;
}

这里发生了什么?为什么T不能成为std::ostream&(*)(std::ostream&)

c++ templates std
1个回答
1
投票

std::endl功能模板。这是IO manipulator。

std::endl<char>std::endl<wchar_t>和无限数量的其他std::endl,每种可能的字符类型一个。编译器不知道您可能指的是哪一个。

它与std::basic_ostream一起使用,因为std::basic_ostream重载了operator<<以接受适用于its字符类型的IO操纵器。记住std::basic_ostream也是模板,std::ostream只是basic_ostream<char>的typedef。

您可能也想为您的班级添加一个,仅用于char

logger & logger::operator<<(std::ostream& (manip)(std::ostream&)) { ... }

编译器会知道您是指哪个endl:需要char流的那个。

© www.soinside.com 2019 - 2024. All rights reserved.