Filip Bartuzi
Filip Bartuzi

Reputation: 5931

Default ofstream class argument in function

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"?

Upvotes: 0

Views: 2480

Answers (3)

user10F64D4
user10F64D4

Reputation: 6661

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);

Upvotes: -2

sehe
sehe

Reputation: 393467

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.

Upvotes: 1

David G
David G

Reputation: 96835

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 */);
}

Upvotes: 2

Related Questions