c++ - 在函数中重载运算符而不写入主体 2 次

标签 c++ arduino operator-overloading

目前,我有这个代码:

void writeLog(__FlashStringHelper* mes){

  Serial.println(mes);

  if(!logfile){
    logfile = SD.open(logpath,FILE_WRITE);
    if(!logfile) return;
  }

  logfile.write(mes);

}

void writeLog(char* mes){

  Serial.println(mes);

  if(!logfile){
    logfile = SD.open(logpath,FILE_WRITE);
    if(!logfile) return;
  }

  logfile.write(mes);

}

有没有办法重载函数来接受 char* 和 __FlashStringHelper* 而无需写入正文 2 次?

谢谢!

最佳答案

如果您可以使用模板,请尝试以下操作:

template <typename T>
void writeLog(T mes) {

    Serial.println(mes);

    if (!logfile) {
        logfile = SD.open(logpath, FILE_WRITE);
        if (!logfile) return;
    }

    logfile.write(mes);

}

关于c++ - 在函数中重载运算符而不写入主体 2 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60617129/

相关文章:

java - Java 中的 Arduino Map 等效函数

c++ - 从结构访问数据时,运算符重载去哪里了?

c++ - 如何在 Windows 下用 C++ 在远程机器上启动一个进程

c++ - 链式 if 和 else if 之间的区别

c++ - 为什么三元运算符常量我的字符串?

c++ - 有运算符时 '=' 没有可行的重载

c++ - 使用重载运算符不明确

数组的 C++ 内存分配

c++ linux双重销毁静态变量。链接符号重叠

java - Arduino 以太网客户端发送 TCP 时出现问题