Search code examples
c++c++11clangfstream

Passing fstream reference as function parameter in C++11


I've just encountered an problem today: The following code seems to work in MSVC++ 2010 but not with Clang LLVM 4.1 (with GNU++11).

#include <fstream>

void foo(std::fstream& file){
    file << "foo";
}
int main() {
   std::fstream dummy("dummy");
   foo(dummy);
   return 0;
}

generates

Invalid operands to binary expression (std::fstream (aka basic_fstream<char>) and const char[4])

on Clang. I thought passing iostream arguments by reference would be common practice in C++. I'm not even sure if this is related to clang, C++11 or anything else.

Any idea how I can pass streams to functions then?


Solution

  • I assume that your original code (that you only partially posted in your original question) looked something like this:

    #include <iosfwd>
    
    void foo(std::fstream& file){
        file << "foo";
    }
    
    int main() {
       std::fstream dummy("dummy");
       foo(dummy);
       return 0;
    }
    

    Indeed, this gives the following error message with clang++ 3.2

    Compilation finished with errors:
    source.cpp:4:10: error: invalid operands to binary expression ('std::fstream' (aka 'basic_fstream<char>') and 'const char [4]')
    file << "foo";
    ~~~~ ^ ~~~~~
    source.cpp:8:17: error: implicit instantiation of undefined template 'std::basic_fstream<char, std::char_traits<char> >'
    std::fstream dummy("dummy");
    ^
    /usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/iosfwd:118:11: note: template is declared here
    class basic_fstream;
    ^
    2 errors generated.
    

    Unfortunately, you only posted the first error message but not the second.

    From the second error message, it is obvious that you only #include <iosfwd> but not #include <fstream>. If you fix that, everything will be OK.

    Please post both the complete code and all the error messages next time.