c++ - How do you create a macro (or other tool) that uses the text of given variables in string format? -


i'm fan of debug printing when trying investigate problems in code:

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

since write code often, awesome if make generic , easier type. maybe this:

debug_macro(foo, bar, baz); 

even though foo, bar, , baz resolve variable names, not strings, possible use variable names create strings "foo:", "bar:", , "baz:"? can write function or macro takes unspecified number of parameters?

if have c++11 can typesafe , neat variadic templates, e.g.:

#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)); } 

the nvp macro here entirely optional , needed if want print name referred in code well.

if want skip nvp bit can use boost pre-processor library (or roll own) e.g.:

#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( ) 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)); } 

for price of odd syntax. example based on this answer. tried use variadic macros solve directly "pure" c++11 solution, turns out recursing through list trickier you'd hope it.


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -