03 template instantiation

C++ Insights – Template Instantiation

Today’s post from Andreas is about template instantiation. C++ Insights helps you a lot to get a deeper insight into this automatic process.

 

03 template instantiation

 

 

The future of C++ speaks templates. It is, therefore, a good idea to get a better view of templates.

Template Instantiation

I’d like to start with a disclaimer at this point. There are other tools to do this job. I saw a preview of Visual Studio which can show you the instantiated template. The same applies to cevelop. It’s not an unique feature that C++ Insights provides here. Except for one difference: it shows you the transformations for all the code you type in at once. Everything! Not just templates.

What I’m talking about is a situation I believe many of us had at least once. There is this function template, a bigger one. We’d like to know for which types it gets instantiated and from where. An easy thing for C++ Insights, the compiler must know this and so does C++ Insights.

Being able to show the code, which effectively runs, is valuable while teaching. I experienced that it helped students a lot if they could see what is going on rather than have to believe me.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    The Laziness of Template Instantiation

    One nice thing C++ Insights shows you is what it doesn’t show. The compiler, at least Clang in which C++ Insights runs, is eager to give us the most efficient code. When it comes to templates, the compiler generates code only for functions or methods which are actually used. You can have a class template with a certain method which is never called. Like here:

    template<typename T>
    class Apple
    {
    public:
      Apple() = default;
      
      bool IsGreen() const { return false; }
      bool IsRed() const { return true; }
    };
    
    int main()
    {
      Apple<int> apple;
      
      if( apple.IsRed()) {}
    }
    

    In this case, the compiler doesn’t generate the method body of that instantiation (Apple<int>) as you can see in C++ Insights:

    template<typename T>
    class Apple
    {
    public:
      Apple() = default;
      
      bool IsGreen() const { return false; }
      bool IsRed() const { return true; }
    };
    
    /* First instantiated from: insights.cpp:13 */
    #ifdef INSIGHTS_USE_TEMPLATE
    template<>
    class Apple<int>
    {  
      public: 
      // inline constexpr Apple() noexcept = default;
      inline bool IsGreen() const;
      
      inline bool IsRed() const;
      
      // inline constexpr Apple(const Apple<int> &) = default;
      // inline constexpr Apple(Apple<int> &&) = default;
    };
    
    #endif
    
    
    int main()
    {
      Apple<int> apple = Apple<int>();
    }
    

    Even if the method is used with a different instantiation (Apple<char>), there will be no code for the int variant. Of course, the method is present for Apple<char>. See for yourself in C++ Insights:

    template<typename T>
    class Apple
    {
    public:
      Apple() = default;
      
      bool IsGreen() const { return false; }
      bool IsRed() const { return true; }
    };
    
    /* First instantiated from: insights.cpp:13 */
    #ifdef INSIGHTS_USE_TEMPLATE
    template<>
    class Apple<int>
    {  
      public: 
      // inline constexpr Apple() noexcept = default;
      inline bool IsGreen() const;
      
      inline bool IsRed() const;
      
      // inline constexpr Apple(const Apple<int> &) = default;
      // inline constexpr Apple(Apple<int> &&) = default;
    };
    
    #endif
    
    
    /* First instantiated from: insights.cpp:14 */
    #ifdef INSIGHTS_USE_TEMPLATE
    template<>
    class Apple<char>
    {  
      public: 
      // inline constexpr Apple() noexcept = default;
      inline bool IsGreen() const
      {
        return false;
      }
      
      inline bool IsRed() const;
      
      // inline constexpr Apple(const Apple<char> &) = default;
      // inline constexpr Apple(Apple<char> &&) = default;
    };
    
    #endif
    
    
    int main()
    {
      Apple<int> apple = Apple<int>();
      Apple<char> cApple = Apple<char>();
      cApple.IsGreen();
    }
    

    This is brilliant because the compiler helps us to generate small binaries. Another view is that it can help to debug, for example, which constructor is used.

    What we can also see with C++ Insights is which line in the original code caused the instantiation. This can be helpful if you do not expect a certain instantiation.

    Class Template Argument Deduction

    When using C++17 and CTAD (class template argument deduction) it can sometimes be less obvious what types you got. Assume this code (I know there it is probably easy to see):

    #include <vector>
    
    int main()
    {
      std::vector v{1,2,3};
      std::vector vd{1.0,2.0,3.0};
    
      //v = vd; // does not compile
    }
    

    We have two std::vectors which each gets three numbers assigned. Despite the fact that these two vectors really look equal we cannot assign vd to v. It might be obvious here, v is of type int while vd is of type double. A fairly easy thing for C++ Insights:

    #include <vector>
    
    int main()
    {
      std::vector<int, std::allocator<int> > v = std::vector<int, std::allocator<int> >{std::initializer_list<int>{1, 2, 3}, std::allocator<int>()};
      std::vector<double, std::allocator<double> > vd = std::vector<double, std::allocator<double> >{std::initializer_list<double>{1.0, 2.0, 3.0}, std::allocator<double>()};
    }
    

    There you can see what type vector really has.

    constexpr if

    While we are talking about C++17, there is another new feature: constexpr if. Let’s have a look at what C++ Insights can do there for us. In the example below we have a stringify template which makes a std::string from the parameter passed to the function:

    #include <string>
    #include <type_traits>
    
    template <typename T>
    std::string stringify(T&& t)
    {
      if constexpr(std::is_same_v<T, std::string>) {
        return t;
      } else {
        return std::to_string(t);
      }
    }
    
    int main()
    {
      auto x = stringify(2);
      auto y = stringify(std::string{"Hello"});
    }
    

    Of course, if we pass in a std::string it just returns this string. The constexpr if helps us to make this entire function template possible. Because there is no to_string function which takes a std::string. With a normal, if this code would not compile.

    Now, what happens, if we pass in a c-string? Like here:

    #include <string>
    #include <type_traits>
    
    template <typename T>
    std::string stringify(T&& t)
    {
      if constexpr(std::is_same_v<T, std::string>) {
        return t;
      } else {
        return std::to_string(t);
      }
    }
    
    int main()
    {
      auto x = stringify(2);
      auto y = stringify("hello");
    }
    

    It will not compile. The reason is, there is also no to_string for a char-array. We can fix this by providing an additional if for this case:

    #include <string>
    #include <type_traits>
    
    template <typename T>
    std::string stringify(T&& t)
    {
      if constexpr(std::is_same_v<T, std::string>) {
        return t;
      } else if constexpr(std::is_array_v< std::remove_reference_t<T> >) {
        return std::string{t};
      } else {
        return std::to_string(t);
      }
    }
    
    int main()
    {
      auto x = stringify(2);
      auto y = stringify("hello");
    }
    

    Now it compiles. What C++ Insights shows you are the template instantiations for the two types. But there is more. It also shows which if-branch is used in that instantiation. If you look closely you can spot something else. C++ Insights shows you also that there is no else if in C++. There is just an if and a else. Why is this important? Because we need to apply the constexpr to all if-branches. Otherwise, we end up with a run-time if in a constexpr if else-branch.

    I’d like to thank Rainer for the opportunity to share information about C++ Insights on his popular blog!

    Have fun with C++ Insights. You can support the project by becoming a Patreon or
    of course with code contributions.

    Stay tuned for more insights about C++ Insights. The next post is about Variadic Templates.

    Andreas

     

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *