我正在处理一个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/plain\n";
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/plain\n";
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::printP的声明是
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另外,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);
}发布于 2013-06-16 20:28:29
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; }重载没有返回类型,为了解决模板中的多义性,它被更改为子类
发布于 2013-06-14 21:34:31
在你的第一个例子中,你用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/plain\n";
server << (const char*) CT_PLAIN;另一种解决方案是向print提供用于const prog_uchar*的重载。
https://stackoverflow.com/questions/17108721
复制相似问题