Explicit template instantiation - when is it used?

前端 未结 4 1282
一整个雨季
一整个雨季 2020-11-22 11:14

After few weeks break, I\'m trying to expand and extend my knowlege of templates with the book Templates – The Complete Guide by David Vandevoorde and Nicolai

4条回答
  •  礼貌的吻别
    2020-11-22 12:10

    If you define a template class that you only want to work for a couple of explicit types.

    Put the template declaration in the header file just like a normal class.

    Put the template definition in a source file just like a normal class.

    Then, at the end of the source file, explicitly instantiate only the version you want to be available.

    Silly example:

    // StringAdapter.h
    template
    class StringAdapter
    {
         public:
             StringAdapter(T* data);
             void doAdapterStuff();
         private:
             std::basic_string m_data;
    };
    typedef StringAdapter    StrAdapter;
    typedef StringAdapter WStrAdapter;
    

    Source:

    // StringAdapter.cpp
    #include "StringAdapter.h"
    
    template
    StringAdapter::StringAdapter(T* data)
        :m_data(data)
    {}
    
    template
    void StringAdapter::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;
    template class StringAdapter;
    

    Main

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

提交回复
热议问题