当前位置:网站首页>Variable length parameter__ VA_ ARGS__ Macro definitions for and logging

Variable length parameter__ VA_ ARGS__ Macro definitions for and logging

2022-04-23 16:54:00 The interview was rejected 10000 times

Macro definition with ’#' Different meanings of characters

With a ‘#’ Convert to string

	#define  _TOSTRING(x)  #x
	int main()
	{
		 auto s1 = _TOSTRING(123);
	     std::cout << " s1  " <<s1 <<std::endl;     //  "123"   return const char*
	}

Take two “##” It's splicing ( Mainly with ##__VA_ARGS__ Together with )

      Replacement part for macro , This operator combines two language symbols into a single language symbol , It provides a means for macro extension to connect actual arguments . It can also be used as digital splicing ,
 But be careful int Value range of , I use this macro to replace ( Connect two strings ) Will report a mistake , Is the wrong parameter , As for why to return int, I don't understand yet , If anyone knows, Sue 
 Tell me 
	#define CONNECT_TWO(x,y)   x##y
	int main()
	{
			 auto s2 = CONNT_TWO(123,456);
    		 std::cout << " s2  " <<s2 <<std::endl;  //  Back to a int Digital splicing of ,123456
	}

Define log macros

 The first one is : Log macro , Be careful. : stay define If it is a multi line definition , You need to add a symbol  '\'
		#define LOG(...){ \
   		             fprintf(stderr,"File:%s  Line:%d  Func:%s \t",__FILE__,__LINE__,__func__ );\
    				 fprintf(stderr,__VA_ARGS__);\
   				     fprintf(stderr,"\n");\
   				 }

The second kind : Let's first understand Predefined macros VA_ARGS

	//  Predefined macros  __VA_ARGS__  You can replace the string represented by the ellipsis in the implementation part of the macro definition 
	//  In the macro definition   Use __VA_ARGS__  Replace  ... 
	#define myPrintf(...) printf(__VA_ARGS__)

In the use of c++ When compiling, you should pay attention to , When connecting variables and strings, you need to add spaces , So the following is fmt There are spaces left and right

	#define error_printf(fmt,...) printf("[ERROR][%s]( %s | %d )" fmt "\n",__FILE__,__FUNCTION__,__LINE__,##__VA_ARGS__)

above Macro definition Can be used as a variable

	  __FILE__ :  The file name is returned 
	  __LINE__ :  It returns the number of rows 
	  __FUNCTION__ :  The function name is returned 

The above is some understanding of my own integration , Refer to the blog address :
Add link description

版权声明
本文为[The interview was rejected 10000 times]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231359046474.html