princetonpku / hccl-archive

Automatically exported from code.google.com/p/hccl-archive
0 stars 0 forks source link

VectorQuaternion의 헤더/소스 분리 #17

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
(박현서군이 다른 이슈의 리플로 남긴 내용을 그대로 
옮겼습니다.)
(앞으로 이런 내용은 이슈로 남겨주세요.)

다음처럼.h와 .cpp로 템플릿을 나누는 걸 고려해 보는 건 
어떨까요?
아래와 같이 설계하면 구현부를 cpp 파일 내로 이동시킬 수 
있습니다.
구현을 cpp 파일 내로 옮기면 헤더 종속성을 줄일 수 있고,
반복되는 template instantiation을 막을 수 있어 컴파일 속도가 
증가합니다.

--------------Super.h-------------------
#ifndef _SUPER_H_
#define _SUPER_H_

template <typename T>
class Super
{
public:
    void hello();
    T a;
};

// available template argument : float, double
// only Super<float>, Super<double> can be used
#ifdef _SUPER_CPP_
template class Super<double>;
template class Super<float>;
#else
extern template class Super<double>;
extern template class Super<float>;
#endif // _SUPER_CPP_

#endif // _SUPER_H_
--------------end of Super.h------------

--------------Super.cpp-----------------
#define _SUPER_CPP_
#include "Super.h"
#include <iostream>

template <typename T>
void Super<T>::hello()
{
    std::cout << a << std::endl;
}
--------------end of Super.cpp----------

단점은
template class Super<double>;
와 같이 explicit template instantiation을 하지 않은 template 
argument는 사용이 불가합니다.
위의 예제에는 float과 double형 외에는 사용이 불가합니다.
물론 본 vector, quaternion 라이브러리에는 float, double 이외에는 
해당 사항이 없어보이므로 괜찮을 것 같습니다.

헤더와 구현부를 나눌 수 있는 기능은 extern template 구문 
덕분인데,
visual studio 2010에서 nonstandard extension이라고 경고가 뜹니다.
찾아본 바로는 vs2005부터 지원되었고, gcc 컴파일러 등에서도 
확장기능으로 제공하며,
새 표준인 C++11에서는 공식 지원되는 사항이므로, 써도 문제 
없을 것 같습니다.

Original issue reported on code.google.com by mec...@gmail.com on 29 Jul 2012 at 9:36

GoogleCodeExporter commented 9 years ago
내 생각엔 어차피 근데 템플릿은 dll로 만들수도 없고해서 
굳이 소스와 헤더를 분리할 필요는 없어보이는데? 
Quaternion이야 그렇다 쳐도, Vector는 int나 size_t, unsigned char 
등이 사용될 경우도 많은데, 이런걸 다 고려해서 explicit 
instantiation을 하는 것도 힘들 것 같고...
컴파일속도야... 1400줄도 채 안되는 코드니깐 그리 문제될 
것도 없어보이고..

다른 사람들은 어떻게 생각해요?

Original comment by mec...@gmail.com on 29 Jul 2012 at 9:41

GoogleCodeExporter commented 9 years ago
템플릿이라고 해도 저렇게 explicit template instantiation해놓고 
인터페이스로 등록하면 dll로 만드는 것이 불가능하지는 
않겠지만... 어차피 따로 dll로 만드는게 호출 오버헤드가 더 
클 수 있으니 그 부분은 그렇다 치고.

컴파일 속도 문제는 template instance가 컴파일 시점에서 각 .obj 
파일마다 중복되어 생성되기 때문에 언급한 듯 한데, 
프로젝트 규모가 클 경우(=파일이 많아질 경우)에는 확실히 
문제가 되지만 그 정도까지 확장될지는 잘 모르겠음.

제일 염려되는 부분이 헤더 종속성인데, 헤더 파일에 STL 
관련 헤더 include 시켰다가 문제가 발생했던 적이 몇 번 
있어서.. 구현을 살펴보니 STL 내용이 포함된 부분이 있던데 
그게 꼭 필요한 거라면 현서 말처럼 분리 시켜놓는 것이 
안전하지 않을까 싶음.

직접 코딩하는 것도 없으면서 말만 하려니 미안하네..;

Original comment by clauxew...@gmail.com on 30 Jul 2012 at 7:36