1

I have opened a file to write to, and according to some conditions sometimes I want to print output to the screen and sometimes to the file. So I edited my function to be like this:

Cacl(const std::string &str, const ofstream &to=std::cout)

But I'm getting an error, what may cause this?

no viable conversion from 'std::__1::ostream' (aka 'basic_ostream<char>') to 'const std::__1::ofstream' (aka 'const basic_ofstream<char>')
void Calculator::solve(const std::string &command, const ofstream &to=std::cout) {

1 Answer 1

6

std::cout is an object of type std::ostream which is a base class of std::ofstream (it's more general than std::ofstream), so you could just do:

void Calculator::solve(const std::string &str, std::ostream &to = std::cout) {
                             // instead of ofstream ^^^^^^^ 

and now you can pass an ofstream object to this function as well.

Also, the ostream shouldn't be const otherwise you won't be able to write to it.

Sign up to request clarification or add additional context in comments.

3 Comments

But now I can't print to it like this: to <<element.first << endl;
invalid operands to binary expression ('const std::ostream' (aka 'const basic_ostream<char>') and 'const std::__1::basic_string<char>') to << element.first << endl;
The argument can't be const. Edited the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.