Simple I / O manipulator does not work as intended

following code:

#include <iostream>

std::ios_base &my_manip (std::basic_ios<char> &os) {
    os.unsetf(std::ios_base::basefield);
    os.setf(std::ios_base::scientific);
    return os;
}

int main (int argc, char **argv) {
    std::cout << 8.8888888 << std::endl;
    std::cout << my_manip << 8.8888888 << std::endl;
    return 0;
}

prints:

8.88889

18.88889

While the following code:

#include <iostream>

std::ios_base &my_manip (std::basic_ios<char> &os) {
    os.unsetf(std::ios_base::basefield);
    os.setf(std::ios_base::scientific);
    return os;
}

int main (int argc, char **argv) {
    std::cout << 8.8888888 << std::endl;
    my_manip(std::cout);
    std::cout << 8.8888888 << std::endl;
    return 0;
}

displays the expected result:

8.88889

8.888889e+00

Can anyone tell me what is wrong with the first version?

+4
source share
3 answers

The user signature of the manipulator does not match,

You must do this:

std::ostream& my_manip (std::ostream &os) {
    os.unsetf(std::ios_base::basefield);
    os.setf(std::ios_base::scientific);
    return os;
}

std::cout << my_manip << 8.8888888 << std::endl;
+5
source

There are three overloads that use a function pointer that can be used for manipulators. Three signatures:

std::ios_base&                  (*)(std::ios_base&)
std::basic_ios<cT, Traits>&     (*)(std::basic_ios<cT, Traits>&);
std::basic_ostream<cT, Traits>& (*)(std::basic_ostream<cT, Traits>&);

Signature you signed ( std::ios_base&(*)(std::basic_ios<cT, Traits>&)) is not anything.

I assume that you are using the actual settings as examples, because the manipulator std::scientificalready implements the logic that the sample code is trying to implement.

+2

, -, .

std::basic_ostream<char> &my_manip (std::basic_ostream<char> &os)

, .

+1

All Articles