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: Paul Baxter,  Meeting C++, Matt Braun, Avi Lachmish, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Dilettant, Marko, Ramesh Jangama, G Prvulovic, Reiner Eiteljörge, Benjamin Huth, and Reinhold Dröge.

Thanks in particular to:  TakeUpCode 450 60

 

Get your e-book at Leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 600 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

Get your interactive course

 

Modern C++ Concurrency in Practice

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

educative CLibrary

Based on my book "Concurrency with Modern C++" educative.io created an interactive course.

What's Inside?

  • 140 lessons
  • 110 code playgrounds => Runs in the browser
  • 78 code snippets
  • 55 illustrations

Based on my book "The C++ Standard Library" educative.io created an interactive course.

What's Inside?

  • 149 lessons
  • 111 code playgrounds => Runs in the browser
  • 164 code snippets
  • 25 illustrations
Tags: templates

Add comment


Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 2307

All 2073011

Currently are 161 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments