A small problem with C++ stream manipulators

i need to make a stream manipulator which takes a number and multiplies it by (-1),something like this:

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

void main() {
    cout << negative << 5 << endl; //output -5
    cout << negative << -4 << endl; // output 4
    system("pause");
}
Last edited on
A somewhat limited version of the output stream manipulator negative
(it is applied if and only if the number immediately follows the manipulator in the stream insertion expression. In addition, it is not generalised to handle output streams other than std::ostream.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <type_traits>

struct sign_manip
{
    std::ostream& stm ;

    template < typename N > friend // arithmetic type, apply the custom format
    typename std::enable_if< std::is_arithmetic<N>::value, std::ostream& >::type
    operator << ( sign_manip manip, N value )
    { return manip.stm << -1 * value ; }

    template < typename T > friend // non-arithmetic type, ignore the custom format
    typename std::enable_if< !std::is_arithmetic<T>::value, std::ostream& >::type
    operator << ( sign_manip manip, const T& value )
    { return manip.stm << value ; }

    struct helper
    { friend sign_manip operator<< ( std::ostream& stm, helper ) { return {stm} ; } };

};

sign_manip::helper negative;

int main()
{
    // numeric types; manipulator negative is applied
    const int n = 23 ;
    std::cout << n << ' ' << negative << n << '\n' ;

    const double n2 = -123.45 ;
    std::cout << n2 << ' ' << negative << n2 << '\n' ;

    std::cout << negative << std::dec << n << '\n' ; // note: manipulator has no effect,
                           // because n does not immediately follow the manipulator


    // not a numeric type; manipulator negative is ignored
    const char* const not_a_number = "not_a_number" ;
    std::cout << not_a_number << ' ' << negative << not_a_number << '\n' ;

}

http://rextester.com/TAZQ91624
Topic archived. No new replies allowed.