C++变量函数和cout

C++ - variadic functions and cout

本文关键字:cout 函数 变量 C++      更新时间:2023-10-16

我有一个接受可变参数的日志记录函数。这对android日志记录和printf来说很好,但我想对std::cout和文件流也这样做。有简单的方法解决这个问题吗?

void LogManagerImpl::LogInfo(const char* msg, ...)
    {
        va_list argptr;
        va_start(argptr, msg);
        /* Log to stdout */
        if (mLogToStdOut)
        {
            #ifdef ANDROID
                __android_log_vprint(ANDROID_LOG_INFO, __ENGINE_LOG_TAG, msg, argptr);
            #elif defined _WIN32 || _WIN64
                //printf ("%s:%s",__ENGINE_LOG_TAG,"INFO:"); vprintf(msg, argptr); printf("n");
                // how do I do the same as above except with for example std::cout?
            #endif
        }
        /* Log to file */
        if (mLogToFile)
        {
                      // TODO
        }
        va_end(argptr);
    }

不要尝试对C++流使用可变包装器,只需使用相应的C API,如vprintf/vnsprintf。以这种方式封装流只会浪费所有的好处,并导致额外的复杂性。

为什么不让你的包装器API使用流,并将它们映射到Android平台上的printf。这样,你就可以获得流的所有好处,而只会在不支持流的平台上失去这些好处。