2

我正在开发一个重载流插入运算符的记录器类。我很难抓住std::flush机械手。

首先,快速总结一下我的工作:

给定一个对象LogClass,我想做以下事情:

LogClass logger;
logger << "Some text" << std::flush;

...并抓住std::flush机械手。

所有输入都直接发送到内部字符串流,以便稍后通过以下内联运算符进行记录(工作正常):

class LogClass
{
    // ...

    std::ostringstream m_internalStream;

    template <typename T>
    LogClass & operator<<(const T & rhs)
    {
        m_internalStream << rhs;
        return *this;
    }

    // ...
};

我试图std::flush通过如下重载来捕获操纵器(这也可以正常工作):

LogClass & LogClass::operator<<(std::ostream & (*manip)(std::ostream &))
{
    std::ostream & (* const flushFunc)(std::ostream &) = std::flush;

    // Is the supplied manipulator the same as std::flush?
    if ((manip == flushFunc)) {
        flush(); // <-- member function of LogClass
    } else {
        manip(m_stream);
    }

    return *this;
}

如果我尝试将局部变量flushFunc设为静态,则问题显示如下:

static std::ostream & (* const flushFunc)(std::ostream &) = std::flush;

在这种情况下,传入manip指针的值等于flushFunc

这是为什么?它与std::flush函数的模板实例化有什么关系char吗?

我正在使用 MS Visual Studio 2010 Pro。

这个问题也显示在这个小的工作代码片段中:

#include <iostream>
#include <iomanip>

int main(int, char **)
{
    static std::ostream & (* const staticFlushPtr)(std::ostream &) = std::flush;
    std::ostream & (* const stackFlushPtr)(std::ostream &) = std::flush;

    std::cout << std::hex <<
            "staticFlushPtr: " << (void *) staticFlushPtr << "\n"
            "stackFlushPtr: " << (void *) stackFlushPtr << "\n";

    return 0;
}

...在我的机器上给出了这个输出:

staticFlushPtr: 013F1078
stackFlushPtr: 0FF10B30

有任何想法吗?

最好的问候, Rein A. Apeland

4

1 回答 1

1

这看起来像是编译器中的一个明确的错误。如果涉及 DLL 或其他类似的东西,我可以理解,或者至少可以找借口,但在你这样一个微不足道的例子中main......(g++ 是正确的。)

我只能建议您在输出中插入一个过滤流缓冲区,它可以捕获对sync.

于 2014-01-16T14:58:32.403 回答