#How to create a function that can take any number of arguments to be used by cout?

10 messages · Page 1 of 1 (latest)

hollow sapphire
#

If you didn't understand the question what i mean is i want to create a function that takes any number of arguments and i want to pass those arguments into cout so that i can print any number of arguments.

Expected Output:

Utils::Log("Hello world", SomefunctionOutput(), 2, 2+2, "Hi");

This is the result i want to achieve. Is there a way? Any help is greatly appreciated!

covert kettleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

hearty python
#

For a printing function you probably want to take by const & instead of by value.

dawn crown
dawn crown
#

an example:

#

void Log()
{
    
}

 template<typename T1, typename... T2>
void Log(const T1& value, const T2&... args)
{
    std::cout << value << '\n';
    Log(args...);
}

int main()
{
    Log("Hello", 3, 2.0f, true);
}```
abstract ingot
#

Worth noting that from C++17 you can express that example more easily using fold expressions:

template <typename... Args>
void Log(const Args&... args) {
  (..., std::cout << args << ' ');
  std::cout << '\n';
}
``` for a (slightly different) example
covert kettleBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.