How do I force a particular instance of a C++ template to instantiate?

后端 未结 6 600
误落风尘
误落风尘 2020-11-29 23:07

See title. I have a template. I want to force a particular instance of a template to instantiate. How do I do this?

More specifically, can you force an abstract temp

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 23:44

    If I understand your question correctly, you have a template class, and you want to force the compiler to generate the code for use with some specific type. For example, you may want to ensure the code for std::vector exists in your program.

    The best way to ensure this is to simply construct an instance of the class:

    void EnsureInstantiation()
    {
        std::vector intvector;
        std::vector boolvector;
        /// etc.
    }
    

    The trick is that you don't even have to call EnsureInstantiation anywhere in your code. Just make sure it's not static or else the compiler may optimize it out.

提交回复
热议问题