How do I prevent implicit template instantiations for a specific template?

I'd like to prevent all implicit template instantiations for a specific templated class in order to prevent it from being instantiated into every translation unit.

It looks like my options are:

  • Use -fno-implicit-templates on gcc's command line. This suppresses all implicit template instantiations, and is not what I want. I only want to prevent it for a single template.
  • Use C++11 "extern template". But this only suppresses specific explicit instantiations. I don't want to type out an "extern template" line for every potential template parameter list this template might be instantiated with.
  • So I need something in-between. It would be nice to have:

     extern template class Foo; // suppress all implicit instantiations of Foo
    

    (Note the lack of template parameter(s).) Any ideas?


    You can split the class like you would with a non-template class. Just put the declarations into a header and include that everywhere, and put the implementation into an .inl/.i file and include that only where you want your template to be instantiated. Alternatively, use compile time switches to do this with a single file - but you do have to separate declaration and implementation.


    you can use std::enable_if which does exactly this with the combination of std::is_same :

    template <class T , typename = std::enable_if <!std::is_same<T,Foo>::value,T>::type >
    class MyClass{
    //...
    };
    

    now myClass won't be compiled for Foo type.


    I would say that the answer to your question is using C++ new type traits to assert the instantiations in your constructor:

    static_assert(std::is_same<TInstantiation, [your-predefined-type]> || std::is_same<TInstantiation, [your-predefined-type2]> /*And so on...*/, "Classname can not be instantiated using this type!");
    

    It's all guaranteed to resolve at compile time :)

    链接地址: http://www.djcxy.com/p/26470.html

    上一篇: 无限滚动不起作用

    下一篇: 如何防止特定模板的隐式模板实例化?