gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:27:10 25 4
gpt4 key购买 nike

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

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

一直很好,直到尝试处理使用 Arduinos P 宏存储的字符数组,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);
}

最佳答案

在您的第一个示例中,您正在调用 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;

另一种解决方案是提供给 print const prog_uchar* 的过载.

关于C++ << 运算符重载和 Arduino 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17108721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com