Foros - Stratos

Programadores => Código de la Semana => Mensaje iniciado por: ethernet en 17 de Noviembre de 2002, 08:46:40 PM

Título: Plantillas para visual c++
Publicado por: ethernet en 17 de Noviembre de 2002, 08:46:40 PM


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//

// __   __ ___  ___  _ __ ___  _ __ ___   ___  _ __

//   / // __|/ _ | '_ ` _ | '_ ` _  / _ | '_

//   V /| (__| (_) | | | | | | | | | | | (_) | | | |

//   _/  ___|___/|_| |_| |_|_| |_| |_|___/|_| |_| v1.09

//

/// file    VCOMMON.H

/// brief   Definiciones comunes utiles

///          Fuentes de varios autores

/// version 1.09

/// todo    

/// bug    

/// warning

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// author  Martin B.R. date 11/06/2001

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// Eurisko software (c) http://www.martinbr.com

/// martin@martinbr.com

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#ifndef _VCOMMON_H

#define _VCOMMON_H



//! Procesador

#if defined(_M_IX86)

# define _PROCESSOR_NAME  "x86"

# define _LITTLE_ENDIAN

#elif defined(_M_MPPC)

# define _PROCESSOR_NAME  "Power Macintosh"

#elif defined(_M_ALPHA)

# define _PROCESSOR_NAME  "Alpha"

#elif defined(_M_MRX000)

# define _PROCESSOR_NAME  "MIPS"

#elif defined(_M_PPC)

# define _PROCESSOR_NAME  "Power PC"

#else

# define _PROCESSOR_NAME  "Unkown"

#endif



//! Plataforma

#if defined(_WIN32)

# define _PLATFORM_NAME "Win32"

# define WIN32_MEAN_AND_LEAN        /// Elimina librerias no usadas

# include "windows.h"

#elif defined(LINUX)

# define _PLATFORM_NAME "Linux"

#endif



#if defined (_MSC_VER)

# define _COMPILER_NAME "Microsoft Visual C++"

# ifdef _DEBUG

#   pragma warning(disable:4800)    /// Forcing value to bool

#   pragma warning(disable:4201)    /// structure/ union without name. (Only relevant on MSVC 5.0)

#   pragma inline_depth(255)        /// Sin limite (8 por defecto)

#   pragma inline_recursion(on)     /// off por defecto

#   pragma auto_inline(on)

#endif



#define INLINE __inline            /// True inline



/// Tipos basicos

#ifndef NULL

# define NULL 0

#endif



#ifndef true

# define true 1

#endif

#ifndef false

# define false 0

#endif



#ifndef TRUE

# define TRUE 1

#endif

#ifndef FALSE

# define FALSE 0

#endif



typedef signed char       S8, schar;    /// Signed 8 bits

typedef unsigned char     U8, uchar;    /// Unsigned 8 bits

typedef signed short      S16, sshort;  /// Signed 16 bits

typedef unsigned short    U16, ushort;  /// Unsigned 16 bits

typedef signed int        S32, sint;    /// Signed 32 bits (16)

typedef unsigned int      U32, uint;    /// Unsigned 32 bits (16)

typedef signed __int64    S64, sint64;  /// Signed 64 bits

typedef unsigned __int64  U64, uint64;  /// Unsigned 64 bits

typedef float             F32;          /// Coma 32 bits

typedef double            F64;          /// Coma 64 bits

typedef unsigned long     UID, DWORD;   /// Identificador unico

typedef void*             HANDLE;

typedef long              RESULT;       /// aka HRESULT



#ifndef OK

# define OK ((RESULT)0x00000000L)

#endif



#ifndef FAIL

# define FAIL ((RESULT)0x80004005L)

#endif



#ifndef ISFAIL

# define ISFAIL(a) ((RESULT)(a)<0)

#endif



/// Constantes

static const F32 FLOAT_ONE  = F32(1.0);

static const F32 FLOAT_ZERO = F32(0.0);



static const S8  S8_MIN  = S8(-128);

static const S8  S8_MAX  = S8(127);

static const U8  U8_MAX  = U8(255);



static const S16 S16_MIN = S16(-32768);

static const S16 S16_MAX = S16(32767);

static const U16 U16_MAX = U16(65535);



static const S32 S32_MIN = S32(-2147483647 - 1);

static const S32 S32_MAX = S32(2147483647);

static const U32 U32_MAX = U32(0xffffffff);



static const F32 F32_MAX = F32(3.402823466e+38F);

static const F32 F32_MIN = F32(1.175494351e-38F);



/// Compiladores que usan el viejo estilo de casting de C++ deben definir _USE_OLD_STYLE_CASTS

#if defined(_USE_OLD_STYLE_CASTS)

# define _CAST(C, T, V) ((T)(V))

#else

# define _CAST(C, T, V) (C<T>(V))

#endif



#define STATIC_CAST(T, V)       _CAST(static_cast, T, V)

#define DYNAMIC_CAST(T, V)      _CAST(dynamic_cast, T, V)

#define REINTERPRET_CAST(T, V)  _CAST(reinterpret_cast, T, V)

#define CONST_CAST(T, V)        _CAST(const_cast, T, V)



#define LOW_BYTE(a)             (((a)&0x00ff))

#define HIGH_BYTE(a)            (((a)>>8))

#define SET_LOW_BYTE(num,low)   ((((num)&0x0000ff00)|LOW_BYTE((low))))

#define SET_HIGH_BYTE(num,high) ((LOW_BYTE(num)|((high)&0x0000ff00)))

#define LOW_WORD(a)             (((a)&0x0000ffff))

#define HIGH_WORD(a)            (((a)>>16))

#define SET_LOW_WORD(num,low)   ((((num)&0xffff0000)|LOW_WORD(low)))

#define SET_HIGH_WORD(num,high) ((LOW_WORD(num)|((high)&0xffff0000)))



#define RED(rgb)                (((rgb)>>16)&0xff)

#define GREEN(rgb)              (((rgb)>>8)&0xff)

#define BLUE(rgb)               ((rgb)&0xff)

#define ALPHA(rgba)             (((rgba)>>24)&0xff)



#define MAKE_RGB16(r,g,b)       (((ushort)(r)<<11)|((ushort)(g)<<5)|(ushort)(b))

#define MAKE_RGB(r,g,b)         (0xff000000|((DWORD)((uchar)(r))<<16)|((DWORD)((uchar)(g))<<8)|(DWORD)((uchar)(b)))

#define MAKE_RGBA(a,r,g,b)      (((DWORD)((uchar)(a))<<24)|((DWORD)((uchar)(r))<<16)|((DWORD)((uchar)(g))<<8)|(DWORD)((uchar)(b)))

#define MAKE_ARGB(a,r,g,b)      ((DWORD)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))



/// Depuracion

#ifdef _DEBUG

# include <cassert>

# undef ASSERT

# define ASSERT(test, msg)                                                                        

 {                                                                                              

   if (!(test))                                                                                  

   {                                                                                            

     static bool bAssert = true;                                                                

     if (bAssert)                                                                                

     {                                                                                          

       static char text[199]="";                                                                

                                                                                                 

       wsprintf(text, "FAILEDt: %sn"                                                          

       "Errort: %sn"                                                                          

       "Filet: '%s':%dnn"                                                                    

       "Abort execution, allow assert Retry, or Ignore in future?",                              

       #test, #msg, __FILE__, __LINE__);                                                        

                                                                                                 

       switch (::MessageBox(NULL, text, "ASSERTION ERROR", MB_ABORTRETRYIGNORE|MB_ICONWARNING))  

       {                                            

         case IDIGNORE:                                                                          

         bAssert = false;                                                                        

         break;                                                                                  

         case IDABORT:                                                                          

         { _asm { int 3 } }                                                                      

       }                                                                                        

     }                                                                                          

   }                                                                                            

 }

# define CHK_SUCCESS(a)     assert(SUCCEEDED(a))

# define CHK_RESULT(a, h)   assert(a == h)

# define CHK_FAILED(a)      { if (ISFAIL(a)) { MessageBox(NULL, #a " Failed!", NULL, MB_OK|MB_ICONERROR); ::ExitProcess(1); } }

# define ODS(a)             OutputDebugString(a)

# define CRASH              { int *a = 0; *a = 1; } /// Peta el ordenador!!

#else

# define ASSERT(test, msg)  ((void)0)

# define CHK_SUCCESS(a)     (a)

# define CHK_RESULT(a, h)   (a)

# define CHK_FAILED(a)      (a)

# define ODS(a)

# define CRASH

#endif



/// Misc

#undef INIT

#define INIT(a)             { (a) = NULL; }



#undef ISOK

#define ISOK(a)             ((a) != NULL)



#undef DELNULL

#define DELNULL(a)          { if ((a) != NULL) { delete (a); (a) = NULL; } }



#undef RELEASENULL

#define RELEASENULL(a)      { if ((a) != NULL) { (a)->Release(); (a) = NULL; } }



#undef DELARRAYNULL

#define DELARRAYNULL(a)     { if ((a) != NULL) { delete[] (a); (a) = NULL; } }



/// FIXMEs / TODOs / NOTEs

#define _QUOTE(a)           #a

#define QUOTE(x)            _QUOTE(x)

#define __FILE__LINE__      __FILE__ "(" QUOTE(__LINE__) ") : "



#define NOTE(a)             message(a)

#define FILE_LINE           message(__FILE__LINE__)



#define todo(a)             message(__FILE__LINE__" TODO :   " #a "n")

#define fixme(a)            message(__FILE__LINE__" FIXME:   " #a "n")



#define TODO(a)             message(__FILE__LINE__"n"  

 " ------------------------------------------------n"

 "|  TODO :   " #a "n"                                

 " ------------------------------------------------n")

#define FIXME(a)            message(__FILE__LINE__"n"  

 " ------------------------------------------------n"

 "|  FIXME :  " #a "n"                                

 " ------------------------------------------------n")



#endif // _VCOMMON_H

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// End Of File

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



Título: Plantillas para visual c++
Publicado por: Zaelsius en 18 de Noviembre de 2002, 09:20:12 AM
Juer, me habeis chafado el código que iba a enviar yo...porque es de similar temática :-)

Es igual, aquí hay más plantillas(algunas realizan funciones similares a las de arriba), aunque éstas trabajan como verdaderas plantillas y no como #defines, la idea es que veais como va esto y os hagais vuestras propias plantillas para fragmentos de código que utiliceis mucho y con diferentes tipos de datos. Son mucho más fáciles de depurar que los #defines.
Teneis este código fuente en http://www.alu.ua.es/j/jgf8/code/safe.h

ZaelsiuS - zsgames.cjb.net



//-----------------------------------------------------------------------------

// File: safe.h

//

// Desc: Plantillas

//

// ZS Games 2002 - Julio Gorgé

//

//-----------------------------------------------------------------------------





#ifndef _SAFE_H

#define _SAFE_H





#include <stdio.h>

#include <memory.h>

#include <winbase.h>





template <class T>

struct SafeZero : public T

{

SafeZero()

{

 ZeroMemory( iface, sizeof(T) );

 dwSize = sizeof( T );

}



}





template <class T>

inline void SafeRelease( T& iface )

{



if(iface)

{

 iface->Release();

 iface = NULL;

}



};



template <class T>

inline void SafeDelete( T& pInstance )

{



if(pInstance !=NULL )

{

 delete pInstance;

 pInstance = NULL;

}



};





#endif // _SAFE_H

Título: Plantillas para visual c++
Publicado por: Astat en 18 de Noviembre de 2002, 01:49:35 PM
                                Supongo que SafeZero() seria algo asi:



SafeZero(T &iface, DWORD &dwSize)

{

 ZeroMemory( iface, sizeof(T) );

 dwSize = sizeof( T );

}



aunque la verdad es que me quedo con el clasico memset(&iface, 0, sizeof(iface)) de toda la vida.

Queda mas elegante y academico hacerlo con templates, pero me parece que es como matar moscas a cañonazos  :ojo: , aparte de la lentitud innecesaria que añades.                                
Título: Plantillas para visual c++
Publicado por: Zaelsius en 18 de Noviembre de 2002, 02:05:31 PM
SafeZero() se utiliza así:





// Inicializa la estructura al declararla

SafeZero<tipodedato> myvar;





aunque caben otras posibilidades, claro...
:-)
Título: Plantillas para visual c++
Publicado por: synchrnzr en 18 de Noviembre de 2002, 03:26:31 PM
                                A mi me suena mucho haber usado esas plantillas pero como macros, yo lo veo mucho más simple (y no necesitas especificar el tipo ;) )



#define SAFE_FREE(p) if(p) delete p;

#define SAFE_RELEASE(p) if(p) p->Release;

#define etc...



Sync