Reputation: 6023
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;
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;
}
prints the expected result:
8.88889
8.888889e+00
Can anybody tell me what is wrong with the first version?
Upvotes: 4
Views: 178
Reputation: 153935
There are three overloads taking a function pointer which can be used for manipulators. The three signatures are
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>&);
The signature you used (std::ios_base&(*)(std::basic_ios<cT, Traits>&)
) is none of these.
I assume you are using the actual settings as examples because the std::scientific
manipulator already implements the logic your example code tries to implement.
Upvotes: 2
Reputation: 47814
The custom manipulator signature is not matching,
You should be doing 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;
Upvotes: 5
Reputation: 55415
The problem seems to be the signature of your manipulator. If you change it to
std::basic_ostream<char> &my_manip (std::basic_ostream<char> &os)
then it works as you expect it to.
Upvotes: 1