C++ How do compilers handle templates

后端 未结 3 1184
孤城傲影
孤城傲影 2021-01-20 19:56

As some of you may know from my recent posts i am studying for a C++ exam which the content for the class was delivered very poorly. I am basically having to self teach ever

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 20:33

    Templates in C++ are implemented through substitution. It's not like Java generics which just type check the code which involves the generics class and then compiles it using raw references (type erasure).

    Basically C++ creates a different class/method for each actual template argument used in your code. If you have your

    template
    void myMethod(T t)
    {
      //
    }
    

    what happens at compile time is that a different method is compiled for each type the template is actually used. If you use it on myMethod(50) and myMethod("foo") then two overloaded version of the method will be available at runtime. Intuitively this means that templates could generate code bloating but in practice the same expressiveness is obtained by a larger codebase without templates with less readability so that's not a real concern.

    So there is no black magic behind them (ok there is if you consider meta programming or partial specialization).

提交回复
热议问题