2 Ekim 2017 Pazartesi

typedef

Giriş
typedef C++'ta çok kullanılır. Karşılığı Java veya C# gibi dillerde yoktur.
C++11
C++11 ile typedef yerine using kelimesi kullanılıyor. Yani şöyle olan kodlar
typedef std::vector<fix_point>::iterator inputIterator;
Bu hale geliyor.
using inputIterator = std::vector<fix_point>::iterator;
Aslında using C#'ta da aynı. Belirtilen tipe bir alias tanımlıyor.

typedef tanımlama
typedef tanımlamak için aşağıdaki her iki söz dizim kuralı da kullanılabilir.
typedef <existing_type> <new_type>
<existing_type> typedef <new_type>  
Kod örneği vermek gerekirse
typedef std::vector<int>::iterator inputIterator;
std::vector<int>::iterator typedef inputIterator;
aynı şeylerdir. Ancak ikinci kullanım şekli tavsiye edilmiyor.
(C11, 6.11.5p1) "The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature."
Array için Typedef
Yukarıdaki genel kural gibi çalışır ancak array'in uzunluğu en sonda belirtilir.

Örnek
Şöyle yaparız
typedef int Room[10][10];
Örnek
array'in parantez içine alınması ve alınmaması fark yaratmaz. Şu iki kod da aynıdır.
typedef int(array)[3];
veya
typedef int array[3];
Ben parantezsiz kullanımı seviyorum. Şöyle yaparız.
typedef int array[6];

array arr={1,2,3,4,5,6};
for(int i=0; i<6; i++)
  cout<<arr[i]<<" ";

typedef yerine macro
typedef yerine macro da kullanabilirdik.Ancak bu kullanım şeklinin genel bazı sakıncaları bulunuyor.
Mesela aşağıdaki kod parçasında d sadece char olarak algılanır.
typedef char *char_ptr;
char_ptr a, b;
#define CHAR_PTR char*
CHAR_PTR c, d;
Ayrıc macroların scope bilgisi yoktur.

Base class içinde typedef
Örnekte typedef template parametresini gizler, val int olarak tanımlanır.
struct Base
{
    typedef int T;
};

template <typename T>
struct Der: public Base
{
    T val;
};
Template içinde typedef
Başka bir template için typedef tanımlanabilir. Şöyle yaparız..
template <size_t N>
struct Vector
{
  typedef Matrix<N, 1> type;
};
Böylece Vector<3>::type şeklinde kullanabiliriz.

Typedef uyumluluğu
Typedef'ler strongly typed değildirler. Birbiri ile uyumlu ancak gerçekte farklı şeyler olan iki tip kullanılsa bile derleyici hata vermeyebilir. Elimizde şöyle typedef'ler olsun.
typedef int EntityID;
typedef int ModelID;
typedef Vector3 Position;
typedef Vector3 Velocity;
Şu kod yanlış.
EntityID eID;
ModelID mID;

if ( eID == mID ) // <- Compiler sees nothing wrong
{ /*bug*/ }


Position p;
Velocity v;

Position newP = p + v; // bug, meant p + v*s but compiler sees nothing wrong

Hiç yorum yok:

Yorum Gönder