Visibility of template specialization of C++ function

前端 未结 9 785
情书的邮戳
情书的邮戳 2021-01-01 11:21

Suppose I have fileA.h which declares a class classA with template function SomeFunc(). This function is implemented directly

9条回答
  •  攒了一身酷
    2021-01-01 12:10

    As Anthony Williams says, the extern template construct is the correct way to do this, but since his sample code is incomplete and has multiple syntax errors, here's a complete solution.

    fileA.h:

    namespace myNamespace {
      class classA {
        public:
          template  void SomeFunc() { ... }
      };
    
      // The following line declares the specialization SomeFunc().
      template <> void classA::SomeFunc();
    
      // The following line externalizes the instantiation of the previously
      // declared specialization SomeFunc(). If the preceding line is omitted,
      // the following line PREVENTS the specialization of SomeFunc();
      // SomeFunc() will not be usable unless it is manually instantiated
      // separately). When the preceding line is included, all the compilers I
      // tested this on, including gcc, behave exactly the same (throwing a link
      // error if the specialization of SomeFunc() is not instantiated
      // separately), regardless of whether or not the following line is included;
      // however, my understanding is that nothing in the standard requires that
      // behavior if the following line is NOT included.
      extern template void classA::SomeFunc();
    }
    

    fileA.C:

    #include "fileA.h"
    
    template <> void myNamespace::classA::SomeFunc() { ... }
    

提交回复
热议问题