strlen () 과 swap () 두 함수 의 실현 (특정 조건 에서).

3085 단어 Datestruct기억float
/**************************
	@author: weedge
	@date: 21/07/2011
	@comment:
	1.             strlen;
		  http://www.cppblog.com/ant/archive/2007/10/12/32886.html
	2. 2  ,         
 *******************************************/
 
#include <iostream>
using namespace std;

//========================swap===================================
/*       */
#define swap1(a,b) {a=a^b;b=a^b;a=a^b;}

/*       */
#define swap11(a,b) {a=a+b;b=a-b;a=a-b;}
#define swap111(a,b) {a=a+b;b=a-b;a=a-b;}

/*        */
#define US(x) (*(unsigned*)(&x)) //       x      。
#define swap2(a,b) {US(a) = US(a) ^ US(b); US(b) = US(a) ^ US(b); US(a) = US(a) ^ US(b);}

/*        。*/
#define USLL(x) (*(unsigned long long*)(&x)) // 64       x      。
#define swap3(a,b)\ 
				{ USLL(a) = USLL(a) ^ USLL(b);\
					USLL(b) = USLL(a) ^ USLL(b);\
					USLL(a) = USLL(a) ^ USLL(b);}

/*   type    。*/
#define swap4(type,a,b) {type temp;temp=a;a=b;b=temp;}

/*         。      WORD       。32  sizeof(long double):12*/
#define swap5(a,b) \
				{ char tempBuf[12];\
					memcpy(tempBuf,&a,sizeof(a));\
					memcpy(&a,&b,sizeof(b));\
					memcpy(&b,tempBuf,sizeof(b)); }


/*     */
template <int N>
struct traits                        //         
{
    typedef void TYPE;
};

template <>
struct traits<sizeof(float)>         //    
{
    typedef unsigned TYPE;
};

template<>
struct traits<sizeof(double)>          //    
{
   typedef unsigned long long TYPE;
};

template <typename T>
typename traits<sizeof(T)>::TYPE &Ref(T &x)           //   x        ,     
{
    return  reinterpret_cast<typename traits<sizeof(T)>::TYPE&>(x);
}

template <typename T>
void myswap(T &a, T &b)                              //    
{
      Ref(a) = Ref(a) ^ Ref(b);
      Ref(b) = Ref(a) ^ Ref(b);
      Ref(a) = Ref(a) ^ Ref(b);
}

//========================strlen===================================
					
/*    */
int str_len(const char *str)
{
	if(*str == '\0') return 0;
	else return str_len(++str)+1;
}

/*     */
char * ToEnd(char * p) 
{ 
    while(*p != '\0') 
        p++; 
    return p; 
}
int mystr_len(char *p) 
{ 
    return ToEnd(p)-p; 
} 

int main()
{
	int a = 1;
	int b = 2;
	float aa = 1.1;
	float bb = 2.2;
	double aaa = -1.11111;
	double bbb = 2.22222;
	
	swap1(a,b); 
	swap2(aa,bb);
	swap3(aaa,bbb);

	cout<<a<<" "<<b<<endl;
	cout<<aa<<" "<<bb<<endl;
	cout<<aaa<<" "<<bbb<<endl;
	
	myswap(a,b);
	myswap(aa,bb);
	myswap(aaa,bbb);
	
	cout<<a<<" "<<b<<endl;
	cout<<aa<<" "<<bb<<endl;
	cout<<aaa<<" "<<bbb<<endl;
	
	char *str = "12345";
	std::cout<<mystr_len(str)<<std::endl;
	
	//cout<<"sizeof(long double):"<<sizeof(long double)<<endl;
		
	return 0;
}

좋은 웹페이지 즐겨찾기