4

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?

ManIkWeet
  • 1,298
  • 1
  • 15
  • 36

1 Answers1

10

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.

Csq
  • 5,775
  • 6
  • 26
  • 39
  • This is beautiful. I had something pretty similar but without the & sign, which might be some lack of my C++ knowledge. Thanks. – ManIkWeet Sep 28 '14 at 08:44
  • @ManIkWeet Yep, that might have been the problem. You can not pass an `ostream` by value (without the `&` sign) because that would mean copying and `ostream`s can not be copied. – Csq Sep 28 '14 at 09:23
  • Makes sense. Did not know that such thing could make so much issues. – ManIkWeet Sep 28 '14 at 09:53
  • After you edited you code, the example doesn't even compile. You forgot to remove `, T t` from arguments of `LogAll()`, and maybe `int logType` too since it's not used anywhere. – Ruslan Apr 12 '15 at 06:26
  • @Ruslan Thanks, fixed. `int logType` comes from the question and it is a nice demonstration of how you can pass additional parameters. – Csq Apr 13 '15 at 17:37