trying to write std:out and file at the same time

前端 未结 2 1346
清歌不尽
清歌不尽 2021-01-06 06:52

I am trying to write to file and stdout at the same time within c++ by overloading ofstream

test.h

 #pragma once 

#include 

using           


        
2条回答
  •  长情又很酷
    2021-01-06 07:54

    The problem

    ofstream::operator << (var);
    

    It's your use of ofstream::operator<< as a qualified function call. You're mandating that the function lookup locate a member function of ofstream; the best match that's a member is the one for void*, whereas the specialisation for char* that prints the actual string contents is a free function (i.e. not a member function).

    You'll find the same problem if you do this with cout, too:

    std::cout.operator<<(var);
    

    The solution

    This might do it:

    static_cast(*this) << var;
    

    because you're still using normal operator syntax (with all the overload resolution that this entails), but doing so with an ofstream as the LHS operand.

    I haven't actually tested it, though.

    Conclusion

    As an aside, your operator<< ought to be a free function too, in order to fit in with this convention.

    So:

    struct OutputAndConsole : std::ofstream
    {
        OutputAndConsole(const std::string& fileName)
           : std::ofstream(fileName)
           , fileName(fileName)
        {};
    
        const std::string fileName;
    };
    
    template 
    OutputAndConsole& operator<<(OutputAndConsole& strm, const T& var)
    {
        std::cout << var;
        static_cast(strm) << var;
        return strm;
    };
    

    I also took the liberty of making some minor syntax adjustments.

提交回复
热议问题