pimpl for a templated class

前端 未结 3 816
攒了一身酷
攒了一身酷 2020-12-30 03:01

I want to use the pimpl idiom to avoid having users of my library need our external dependencies (like boost, etc) however when my class is templated that seems to be imposs

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 03:42

    You can explicitly instantiate templates in the source file, but that is possible only if you know what the template type is going to be. Otherwise, do not use pimpl idiom for templates.

    Something like this :

    header.hpp :

    #ifndef HEADER_HPP
    #define HEADER_HPP
    
    template< typename T >
    class A
    {
      // constructor+methods + pimpl
    };
    
    #endif
    

    source.cpp :

    #include "header.hpp"
    
    // implementation
    
    // explicitly instantiate for types that will be used
    template class A< int >;
    template class A< float >;
    // etc...
    

提交回复
热议问题