Generics in C#, Java, and C++

Tags:

Generics in C#, Java, and C

안그래도 generics에 관심이 폭증하던차에
이런 좋은글을 만났네요.

Definition of Generics

Anders Hejlsberg: Generics is essentially the ability to have type parameters on your type. They are also called parameterized types or parametric polymorphism.

결국 Parmeterized Polymorphism 이상으로 잘 정의하는건 없다고 생각되네요.
쉽게말해 List<int>, List<double> 과 같은것들.

또 generics하면 나오는,

http://en.wikipedia.org/wiki/Metaprogramming_%28programming%29

Metaprogramming is the writing of programs that write or manipulate other programs (or themselves) as their data or that do part of the work that is otherwise done at runtime during compile time. This allows programmers to produce a larger amount of code and get more done in the same amount of time as they would take to write all the code manually.

물론 이 정의가 틀렸다고 하는 사람들도 있음.
http://c2.com/cgi/wiki?MetaProgramming

어쨌거나, 메타 프로그래밍하면 C++의 템플릿이..

http://en.wikipedia.org/wiki/Template_metaprogramming

template <int N>
struct Factorial {
  enum { value = N * Factorial<N – 1>::value };
};

template <>
struct Factorial<1> {
  enum { value = 1 };
};

// Factorial<4>::value == 24

중간에 나오는 enum hack에 유의. const 로 선언하면 컴파일 타임에 그 값을
이용할 수 없다고 불평하는 수가 있고, 따라서 이와같은 경우 const와 동일한
효과를 얻기 위해 enum을 사용하는 기법입니다.

이와같은건 당연히 자바로는 안되죠.
자바는 단지 erasure에 불과하니까요.

C#은 실행시간에 instantiation된다는 점에서 C++과 같은 효율성을
갖추지 못할 수 있죠. (약한 표현에 유의. 최근의 JTI들은 컴파일러보다
유능할 수 있음이 기본 모토이니까요.) 그러나 strongly typed이면서,
개별 parameterized class가 코드를 공유하고 VT table을 별개로
가지는 매우 효율적인 구조입니다.

C++은 반면에 컴파일 또는 링크 타임에 코드를 펼치죠. 즉, List of int 와 List of double이
별개로 만들어집니다.

결국 그 효율성과 디자인면에서 C# > C++ > JAVA 순으로 저는 점수를
주고 싶군요.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *