How to create a macro (or other tool) that uses the text of these variables in string format?

I am a fan of debugging printing when trying to figure out problems in my code:

cout << "foo:" << foo << "bar:" << bar << "baz:" << baz;

Since I write code so often, it would be great if I could make it general and easier to type. Maybe something like this:

DEBUG_MACRO(foo, bar, baz);

Even if foo, barand they bazallow variable names, not strings, can their variable names be used to create strings "foo:", "bar:"and "baz:"? Can you write a function or macro that takes an indefinite number of parameters?

+5
source share
3 answers

++ 11, - , :

#include <string>
#include <iostream>

template <typename T>
void debug(const T& v) {
  std::cout << v << "\n";
}

template <typename T, typename... Tail>
void debug(const T& v, const Tail& ...args) {
  std::cout << v << " ";
  debug(args...);
}

#define NVP(x) #x":", (x)

int main() {
  int foo=0;
  double bar=0.1;
  std::string f="str";
  debug(NVP(foo),NVP(bar),NVP(f));
}

NVP , , , .

NVP, Boost ( ), :

#include <string>
#include <iostream>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>

template <typename T>
void debug_impl(const T& v) {
  std::cout << v << "\n";
}

template <typename T, typename... Tail>
void debug_impl(const T& v, const Tail& ...args) {
  std::cout << v << " ";
  debug_impl(args...);
}

#define NVP(x) #x":", (x)
#define MEMBER( r, data, i, elem ) BOOST_PP_COMMA_IF( i ) NVP(elem)

#define debug( members )                                \
  debug_impl(                                           \
  BOOST_PP_SEQ_FOR_EACH_I( MEMBER,, members )           \
  )


int main() {
  int foo=0;
  double bar=0.1;
  std::string f="str";
  debug((foo)(bar)(f));
}

. . , "" ++ 11, , , .

+4
#define DEBUG_MACRO(name) std::cout << #name << " = " << name << std::endl;

: http://ideone.com/agw4i

+1

, ?

, .

, , elipses :

int foo(string foo, ...)

. , . , , :

int n = 42;
char buf[256] = {};
sprintf(buf, "%s", n);

This is mistake. I specified a string, but passed int. The best case scenario is the first time I debug my program and explode immediately. It is much more likely, however, that the code will never work until the first time there is an exceptional condition in production, and then it starts your entire program in the middle of the trading day. Customers will call and shout at you, cancel units, etc. .... Well, I’m dramatic, but the fact is that type safety is your friend , even if you have a love and hate relationship with him.

0
source

All Articles