Search code examples
c++c++11templatesostreamansi-c

How to pass other variables as args along with std::ostream in a function in C++?


I was working on a function which looks like so:

inline std::ostream& mvUp(int n,std::ostream& ss){
    char u[8];
    sprintf(u,"\033[%dA",n);
    ss<<u;
    return ss;
}

and using it like so:

std::cout<<mvUp(1);

however it shows error:

std::cout<<mvUp(1);
     |          ^_____too few args in function call
     ^_______________no operator "<<" match these operands

I also tried: std::cout<<mvUp(1,std::cout); but still not working.

std::cout<<mvUp(1);
     ^_______________no operator "<<" match these operands

now when I try making it template,

template <int n>
inline std::ostream& mvUp(std::ostream& ss){
    char u[8];
    sprintf(u,"\033[%dA",n);
    ss<<u;
    return ss;
}

and use it: std::cout<<mvUp<1>, this works totally fine but the problem with this is that templates take const args.

Not able to figure out where am I getting wrong. Also how is it working in templates when I am not passing any args?


Solution

  • Modern C++ code uses std::string, and other classes. This makes implementing this kind of an overload trivial.

    #include <string>
    #include <sstream>
    
    inline std::string mvUp(int n) {
        std::ostringstream o;
    
        o << "\033[" << n << "A";
        return o.str();
    }
    

    Then, everything will work automatically:

    std::cout<<mvUp(1);
    

    Your mvUp returns std::string, and the existing << overload takes care of the rest.