Tim*_*ski 3 c++ templates operator-overloading arduino
我正在开发一个arduino项目,我使用以下模板使用<<运算符打印各种数据类型
template<class T>
inline Print &operator <<(Print &obj, T arg)
{ obj.print(arg); return obj; }
Run Code Online (Sandbox Code Playgroud)
在尝试处理使用Arduinos P宏存储的char数组之前一直没有问题,后者将数据存储在flash而不是ram中
//params stored in flash using P() from webduino library
P(CT_PLAIN) = "text/plain\n";
server << CT_PLAIN;
Run Code Online (Sandbox Code Playgroud)
这导致编译器错误
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
Run Code Online (Sandbox Code Playgroud)
虽然以下编译
//params stored in flash using P() from webduino library
P(CT_PLAIN) = "text/plain\n";
server.printP(CT_PLAIN);
Run Code Online (Sandbox Code Playgroud)
我试图创建一个<<运算符重载,但我不完全理解语法和方法,我已经研究了几个小时无济于事,并将高度感谢任何反馈.
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; }
Run Code Online (Sandbox Code Playgroud)
虽然我仍然得到相同的编译错误.
WebServer :: printP的声明是
void printP(const prog_uchar *str);
Run Code Online (Sandbox Code Playgroud)
任何反馈和帮助将受到高度赞赏!
完整的编译器错误:
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
Run Code Online (Sandbox Code Playgroud)
另外还有WebServer :: printP的定义
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);
}
Run Code Online (Sandbox Code Playgroud)
事情是在你的第一个例子中,你正在调用printP(const prog_uchar*)一个const prog_uchar[12]可以轻易转换为的类型的参数const prog_uchar*.
在使用时operator<<,您使用print()类型对象调用函数,const prog_uchar[12]但是没有print适合此类型的任何重载.因此,编译器会查找不同的print重载并采用最合适的重载.但是,在您的情况下,不仅有一个"最合适的"重载,而且其中有8个,因此最终会有详细的错误消息.
解决您的问题的方法是明确地将您要打印的内容转换为const char*:
P(CT_PLAIN) = "text/plain\n";
server << (const char*) CT_PLAIN;
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是提供print过载const prog_uchar*.