명시 적으로 몇 가지 유형에 대해서만 작업하려는 템플릿 클래스를 정의하는 경우.
일반 클래스처럼 헤더 파일에 템플릿 선언을 넣습니다.
템플릿 정의를 일반 클래스처럼 소스 파일에 넣으십시오.
그런 다음 소스 파일의 끝에서 사용 가능하게하려는 버전 만 명시 적으로 인스턴스화하십시오.
바보 예 :
// StringAdapter.h
template<typename T>
class StringAdapter
{
public:
StringAdapter(T* data);
void doAdapterStuff();
private:
std::basic_string<T> m_data;
};
typedef StringAdapter<char> StrAdapter;
typedef StringAdapter<wchar_t> WStrAdapter;
출처 :
// StringAdapter.cpp
#include "StringAdapter.h"
template<typename T>
StringAdapter<T>::StringAdapter(T* data)
:m_data(data)
{}
template<typename T>
void StringAdapter<T>::doAdapterStuff()
{
/* Manipulate a string */
}
// Explicitly instantiate only the classes you want to be defined.
// In this case I only want the template to work with characters but
// I want to support both char and wchar_t with the same code.
template class StringAdapter<char>;
template class StringAdapter<wchar_t>;
홈페이지
#include "StringAdapter.h"
// Note: Main can not see the definition of the template from here (just the declaration)
// So it relies on the explicit instantiation to make sure it links.
int main()
{
StrAdapter x("hi There");
x.doAdapterStuff();
}
그래는 MSVC CRT 라이브러리는 모든 스트림, 로케일 및 문자열 클래스의 명시 적 인스턴스 생성을 전문 char 및 wchar_t. 결과 .lib는 5 메가 바이트 이상입니다. –
컴파일러는 템플릿이 다른 곳에서 명시 적으로 인스턴스화되었음을 어떻게 알 수 있습니까? 클래스 정의가 생성 되었기 때문에 클래스 정의를 생성하지 않습니까? –
@STing : 템플릿이 인스턴스화되면 심볼 테이블에 해당 함수가 입력됩니다. – kennytm