Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringstream with recursive variadic function?

I want to be able to combine multiple different arguments into a single string using ostringstream. That way I can log the resulting single string without any random issues.

I got this far:

template <typename T>
    void MagicLog(T t)
    {
        std::cout << t << std::endl;
    }

    template<typename T, typename... Args>
    void MagicLog(T t, Args... args) // recursive variadic function
    {
        std::cout << t << std::endl;

        MagicLog(args...);
    }

    template<typename T, typename... Args>
    void LogAll(int logType, T t, Args... args)
    {
        std::ostringstream oss;
        MagicLog(t);
        MagicLog(args...);
        //Log(logType, oss.str());
    }

So I need to replace std::cout with the oss that I made in the LogAll function, I tried passing it as an argument to the other functions but it was complaining about a "deleted function"...

So: How can I get a recursive variadic function to accept another parameter, the ostringstream?

like image 827
ManIkWeet Avatar asked Jan 10 '23 17:01

ManIkWeet


1 Answers

I don't really understand your problem. Just like what you did with your LogAll function, passing an ostream& as first parameter works like a charm:

#include <iostream>
#include <sstream>

template <typename T>
void MagicLog(std::ostream& o, T t)
{
    o << t << std::endl;
}

template<typename T, typename... Args>
void MagicLog(std::ostream& o, T t, Args... args) // recursive variadic function
{
    MagicLog(o, t);
    MagicLog(o, args...);
}

template<typename... Args>
void LogAll(int logType, Args... args)
{
    std::ostringstream oss;
    MagicLog(oss, args...);
    std::cout << oss.str();
}

int main()
{
  LogAll(5, "HELLO", "WORLD", 42);
}

It was also possible to eliminate the duplicate code from your MagicLog function.

like image 85
Csq Avatar answered Jan 23 '23 03:01

Csq