C++ <<运算符重载和模板与 Arduino

C++ << operator overloading and templates with Arduino

本文关键字:lt Arduino 重载 运算符 C++      更新时间:2023-10-16

我正在做一个arduino项目,我一直在使用以下模板使用<<运算符打印各种数据类型

template<class T>
inline Print &operator <<(Print &obj, T arg)
{ obj.print(arg); return obj; }

这一直很好,直到尝试处理使用 Arduinos P 宏存储的字符数组,该宏将数据存储在闪存而不是 ram 中

//params stored in flash using P() from webduino library
P(CT_PLAIN) = "text/plainn";
server << CT_PLAIN;

这会导致编译器错误

httpServer.h : : In function 'Print& operator<<(Print&, T) [with T = const prog_uchar*]':
httpServer.cpp : instantiated from here
httpServer.h : call of overloaded 'print(const prog_uchar*&)' is ambiguous

虽然以下编译

//params stored in flash using P() from webduino library
P(CT_PLAIN) = "text/plainn";
server.printP(CT_PLAIN);

我试图创建一个<<运算符重载,但我不完全理解语法和方法,我已经研究了几个小时无济于事,非常感谢任何反馈。

 WebServer &operator <<(WebServer &server,const prog_uchar *str)
 { server.printP(str); }
 template<class T>
 inline Print &operator <<(Print &obj, T arg)
 { obj.print(arg); return obj; }

虽然我仍然收到相同的编译器错误。

WebServer::p rintP 的声明是

 void printP(const prog_uchar *str);

任何反馈和帮助将不胜感激!

完整的编译器错误:

 Compiling 'webapp' for 'Arduino Mega 2560 or Mega ADK'
 httpServer.h : : In function 'Print& operator<<(Print&, T) [with T = const prog_uchar*]':
 httpServer.cpp : instantiated from here
 httpServer.h : call of overloaded 'print(const prog_uchar*&)' is ambiguous
 Print.h : print(const String&) <near match>
 Print.h : print(const char*) <near match>
 Print.h : print(char) <near match>
 Print.h : print(unsigned char, int) <near match>
 Print.h : print(int, int) <near match>
 Print.h : print(unsigned int, int) <near match>
 Print.h : print(long int, int) <near match>
 Print.h : print(long unsigned int, int) <near match>
 Error compiling

另外Web服务器的定义::p rintP

 void WebServer::printP(const prog_uchar *str)
 {
 // copy data out of program memory into local storage, write out in
 // chunks of 32 bytes to avoid extra short TCP/IP packets
   uint8_t buffer[32];
   size_t bufferEnd = 0;
   while (buffer[bufferEnd++] = pgm_read_byte(str++))
   {
     if (bufferEnd == 32)
     {
       m_client.write(buffer, 32);
       bufferEnd = 0;
     }
   }
   // write out everything left but trailing NUL
   if (bufferEnd > 1)
     m_client.write(buffer, bufferEnd - 1);
 }

问题是在你的第一个示例中,你用一个 const prog_uchar[12] 类型的参数调用printP(const prog_uchar*),该参数可以简单地转换为 const prog_uchar* .

当您使用 operator<< 时,您将使用类型 const prog_uchar[12] 的对象调用函数print(),但您没有任何适合此类型的print重载。因此,编译器会查找不同的重载print并采取最合适的重载。但是,在您的情况下,不仅有一个"最合适"的重载,而且有 8 个,因此您最终会看到详细的错误消息。

问题的解决方案是显式地将您尝试打印的内容转换为const char*

P(CT_PLAIN) = "text/plainn";
server << (const char*) CT_PLAIN;

另一种解决方案是为const prog_uchar*提供print过载。

 WebServer &operator <<(WebServer &server,const prog_uchar *str)
 { server.printP(str); return server;}
 template<class T>
 inline WebServer &operator <<(WebServer &obj, T arg)
 { obj.print(arg); return obj; }

重载没有返回类型,为了解决模板中的歧义,它被更改为子类