0

I've got function. If user didn't provide ofstream element into this function:

bool isPolpierwsza(int, bool = false, ofstream = NULL);

than I want to asign "plik"

bool isPolpierwsza(int liczba, bool wypisz, ofstream plik)

to NULL value.

My compiler put error:

2.9.cpp:5:48: error: no viable conversion from 'long' to 'ofstream' (aka 'basic_ofstream')
bool isPolpierwsza(int, bool = false, ofstream = NULL);

How to setup default value to ofstream to be treated like NULL or "false"?

David G
  • 94,763
  • 41
  • 167
  • 253
Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102
  • 1
    What does this have to do with C#? – Jon Skeet Oct 19 '13 at 18:22
  • 1
    Overload it with a different function. It is C++, after all. so provide two versions; one without the stream (which should be a reference in the first place). – WhozCraig Oct 19 '13 at 18:27
  • 1
    `ofstream` is not a pointer. You can't set it to `NULL`. The `NULL` macro is most probably defined as `0L`, hence this error. –  Oct 19 '13 at 18:27
  • There is no such thing as "a null value" generally. Some types (e.g. pointers or optional types) have such a notion, but most types don't. – Kerrek SB Oct 19 '13 at 18:30

3 Answers3

2

You can use two overloads, one of which doesn't take the std::ofstream argument:

bool isPolpierwsza(int liczba, bool wypisz)
{
    return isPolpierwsza(liczba, wypisz, /* your own argument */);
}
David G
  • 94,763
  • 41
  • 167
  • 253
1

You could pass the stream buffer instead:

bool isPolpierwsza(int, bool = false, std::streambuf* osbuf = nullptr)
{
    std::ostream os(osbuf? osbuf : std::cout.rdbuf());
    os << "yay it works\n";
    return false;
}

Now, call it like this:

std::ofstream ofs("myoutput.txt");
bool result = isPolpierwsza(42, true, ofs.rdbuf());

Or indeed, without the parameter.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • @0x499602D2 Well, this feels more like in the spirit of the IOStream library design (which I know, hurts many people's eyes) – sehe Oct 19 '13 at 19:45
-2

First of all, it may be useful to use ostream instead of ofstream, as this is more general and considered better practice.

Then, you can simply assign 'cout' instead of 'NULL'. NULL doesn't work because ostream is not a pointer but a struct. This means the struct has to be filled out completely and can not be assigned NULL. Instead, you could use cout, like

bool isPolpierwsza(int, bool = false, ostream& = cout);
user10F64D4
  • 6,531
  • 1
  • 13
  • 12