IT TIP

명시 적 인스턴스화-언제 사용됩니까?

itqueen 2020. 10. 29. 20:19
반응형

명시 적 인스턴스화-언제 사용됩니까?


몇 주 휴식 후, 저는 Templates – The Complete Guide by David Vandevoorde와 Nicolai M. Josuttis 책을 통해 템플릿에 대한 지식을 확장하고 확장 하려고합니다. 지금 이해하려는 것은 템플릿의 명시 적 인스턴스화입니다. .

실제로 메커니즘에 문제가있는 것은 아니지만이 기능을 사용하고 싶거나 사용하고 싶은 상황은 상상할 수 없습니다. 누군가 나에게 그것을 설명 할 수 있다면 나는 더 감사 할 것이다.


https://docs.microsoft.com/en-us/cpp/cpp/explicit-instantiation 에서 직접 복사 :

명시 적 인스턴스화를 사용하여 코드에서 실제로 사용하지 않고도 템플릿 클래스 또는 함수의 인스턴스화를 만들 수 있습니다. 때문에 당신이 라이브러리 (lib 디렉토리)를 만드는 것을 사용하는 템플릿 파일을 때이 유용 배포를 인스턴스화하지 템플릿 정의 개체 (.OBJ) 파일에 넣어되지 않습니다.

(예를 들어, 된 libstdc는 ++의 명시 적 인스턴스를 포함 std::basic_string<char,char_traits<char>,allocator<char> >(인 std::string) 당신의 기능을 사용할 때마다 때문에 std::string, 동일한 기능 코드가 객체에 복사 할 필요가 없습니다. 전용 (링크) 된 libstdc에 그 ++를 참조 할 필요가 컴파일러를.)


몇 가지 명시 적 유형에 대해서만 작업하려는 템플릿 클래스를 정의하는 경우.

일반 클래스처럼 헤더 파일에 템플릿 선언을 넣으십시오.

일반 클래스처럼 소스 파일에 템플릿 정의를 넣습니다.

그런 다음 소스 파일의 끝에서 사용하려는 버전 만 명시 적으로 인스턴스화합니다.

어리석은 예 :

// 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();
}

컴파일러 모델에 따라 다릅니다. 분명히 Borland 모델과 CFront 모델이 있습니다. 그리고 그것은 또한 당신의 의도에 달려 있습니다. 만약 당신이 라이브러리를 작성한다면, 당신은 (위에서 언급했듯이) 당신이 원하는 전문화를 명시 적으로 인스턴스화 할 수 있습니다.

GNU C ++ 페이지는 https://gcc.gnu.org/onlinedocs/gcc-4.5.2/gcc/Template-Instantiation.html 여기에서 모델에 대해 설명합니다 .

참고 URL : https://stackoverflow.com/questions/2351148/explicit-instantiation-when-is-it-used

반응형