C++ Insights - Template Instantiation

Contents[Show]

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 is able to show you the instantiated template. The same applies for cevelop. It’s not a 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 to have to believe me.

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, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Darshan Mody, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Wolfgang Gärtner,  Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Avi Kohn, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, Sudhakar Balagurusamy, lennonli, and Pramod Tikare Muralidhara.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, and Dendi Suhubdy

 

Seminars

I'm happy to give online-seminars or face-to-face seminars world-wide. Please call me if you have any questions.

Bookable (Online)

Deutsch

English

Standard Seminars 

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

New

Contact Me

Modernes C++,

RainerGrimmSmall

 

Tags: templates

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 847

Yesterday 8573

Week 9421

Month 167852

All 5037166

Currently are 127 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments