Categories > Coding > C++ >

C++ lua print-equivalent

0x90

dingleberry#2286

vip

Posts: 249

Threads: 26

Joined: Dec, 2020

Reputation: 28

Posted

Made this in 10 seconds, cool and stuff I guess, for anyone transitioning directly from lua to C++.

template <typename... T>
void print(T&&... args)
{
    ((std::cout << args << '\t'), ...);
}

works because the template defines a variadic template that can take any type, and in the actual function declaration T&& is an rvalue reference, saying you can not only take a value but references any variables passed.

The line after is a fold expression going through each argument in the template and applying the std::cout rule to it.

 

here's some example code

#include <iostream>

template <typename... T>
void print(T&&... args)
{
    ((std::cout << args << '\t'), ...);
}

int main()
{
  int a = 6;
  print("hello", "world", 3, 4, 5, a); // hello   world   3   4   5   6   
}
  • 0

Posts: 2100

Threads: 10

Joined: Sep, 2020

Reputation: 62

Replied

Vouch 90 is big brain

  • 0

Discord : Doctor Doom#0550

Users viewing this thread:

( Members: 0, Guests: 1, Total: 1 )