首页 > 解决方案 > 在函数中重载运算符而不编写正文 2 次

问题描述

目前,我有这个代码:

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 次?

谢谢!

标签: c++arduinooperator-overloading

解决方案


如果你可以使用模板试试这个:

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

    Serial.println(mes);

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

    logfile.write(mes);

}

推荐阅读