簡體   English   中英

函數的重載流運算符

[英]overload stream operator for function

我很好奇是否可以為函數重載<<流運算符?

我在Windows上使用OutputDebugString寫入日志,並且它僅接受字符串。

我想知道是否可以在c ++中編寫一個函數,在其中可以包裝OutputDebugString並執行以下操作

MyLogFuntion() << string << int << char;

您可以從函數中返回一個具有operator <<的對象,然后在該對象的析構函數中進行記錄。 然后,當您調用MyLogFunction() ,它將創建一個臨時對象,該對象將存儲插入其中的所有數據,然后在該對象結束時,在該對象結束時將其輸出。

這是一個示例 (沒有實際上是多余的logger功能)

#include <iostream>
#include <sstream>


class Logger {
    std::stringstream ss;
public:
    ~Logger() {
      // You want: OutputDebugString(ss.str()); 
      std::cout<< ss.str(); 
    }

    // General for all types supported by stringstream
    template<typename T>
    Logger& operator<<(const T& arg) {
       ss << arg;
       return *this;
    }

    // You can override for specific types
    Logger& operator<<(bool b) {  
       ss << (b? "Yep" : "Nope");
       return *this;
    }
};


int main() {
    Logger() << "Is the answer " << 42 << "? " << true;
}

輸出:

答案是42嗎? 是的

您不能以您想要的方式提供重載。

如果必須使用的方法(在您的情況下為OutputDebugString強迫您提供std::string (或類似的)參數,則必須以某種方式提供該參數。 一種方法是使用std::stringstream ,將其流式傳輸,然后將結果傳遞給OutputDebugString

std::stringstream ss;
ss << whatever << " you " << want << to << stream;
OutputDebugString(ss.str());

如果您確實希望事情變得更緊湊,也可以將其轉儲到宏中:

#define OUTPUT_DEBUG_STRING(streamdata)   \
  do {                                    \
    std::stringstream ss;                 \
    ss << streamdata;                     \
  } while (0)

然后寫

OUTPUT_DEBUG_STRING(whatever << " you " << want << to << stream);

另一種選擇是圍繞OutputDebugString編寫一個更復雜的包裝器類,該類提供流運算符。 但這可能不值得付出努力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM