C++ Core Guidelines: Template Interfaces

Contents[Show]

This post is about template interfaces which are due to the C++ core guidelines: "...a critical concept", because a template interface is "a contract between a user and an implementer - and should be carefully designed.".

automatic

Here are the rules for today:

Let me start with the first rule T.41:

T.41: Require only essential properties in a template’s concepts

What does it mean to specify only the essential properties? The guidelines provide an example of a sort algorithm which has debug support.

template<Sortable S>
    requires Streamable<S>
void sort(S& s)  // sort sequence s
{
    if (debug) cerr << "enter sort( " << s <<  ")\n";
    // ...
    if (debug) cerr << "exit sort( " << s <<  ")\n";
}


Now, one question remains: What is the issue if you specify non-essential properties. This means that your concepts are strongly bound to the implementation. The result may be that a small change of the implementation changes your concepts. In the end, your interface becomes quite unstable. 

T.42: Use template aliases to simplify notation and hide implementation details

Since C++11 we have templates aliases. A template alias is a name that refers to a family of types. Using them makes your code more readable and helps you to get rid of type traits. My previous post  C++ Core Guidelines: Definition of Concepts, the Second provides more information to type traits.

Let's see what the guidelines mean by readability. The first example uses type traits:

template<typename T>
void user(T& c)
{
    // ...
    typename container_traits<T>::value_type x; // bad, verbose
    // ...
}

Here is the corresponding case with template aliases.

template<typename T>
using Value_type = typename container_traits<T>::value_type;

void user2(T& c)
{
    // ...
    Value_type<T> x;
    // ...
}


Readability is also the argument which holds for the next rule

T.43: Prefer using over typedef for defining aliases

There are two arguments from the readability perspective to prefer using over typedef. First, using comes first when used. Second, using feels quite similar to auto. Additionally, using can easily be used for template aliases.

typedef int (*PFI)(int);     // OK, but convoluted

using PFI2 = int (*)(int);   // OK, preferred

template<typename T>
typedef int (*PFT)(T);       // error (1) 

template<typename T>
using PFT2 = int (*)(T);     // OK


The first two lines define a pointer to a function (PFI and PFI2) which takes an int and returns an int. In the first case typedef is used and in the second line using. The last two lines define a function template (PFT2) which takes a type parameter T and returns an int.  The line (1) is not valid.

T.44: Use function templates to deduce class template argument types (where feasible)

The primary reason that we have too many make_ functions such as std::make_tuple or std::make_unique is that a function template can deduce its template arguments from its function arguments. During this process, the compiler applies a few simple conversions such as removing the outermost const/volatile qualifier and decaying C-arrays and functions to a pointer to the first element of the C-arrray or a pointer to the function.

This automatic template argument deduction makes our life as a programmer much easier.

Instead of typing

std::tuple<int, double, std::string> myTuple = {2011, 20.11, "C++11"};

 

you use the factory function std::make_tuple.

auto myTuple = std::make_tuple(2011, 20.11, "C++11");

 

Sad to say but automatic template type deduction is in C++ only available for function templates. Why? Constructors of class templates are a special static function. Right! With C++17, the compiler can deduce its template arguments from its constructor arguments. Here is the way to define myTuple in C++17.

std::tuple myTuple = {2017, 20.17, "C++17"};

 

An obvious effect of this C++17 feature is that most of the make_ function become obsolete with C++17.

If you want to know the details about class template argument deduction including the argument deduction guide, read the post Modern C++ Features - Class Template Argument Deduction from Arne Mertz.

Teachability of C++

I have to admit, I like this C++17 feature. As a C++ trainer, my job is it to explain this difficult stuff. The more symmetric C++ becomes the easier is it for me to speak about the general ideas.  Now I can say: "A template can automatically deduce its template arguments from its function arguments.".  In the past, I had to say this works only for function templates.

Here is a simple example:

// templateArgumentDeduction.cpp

#include <iostream>

template <typename T>
void showMe(const T& t){
  std::cout << t << std::endl;
}

template <typename T>
struct ShowMe{
  ShowMe(const T& t){
    std::cout << t << std::endl;
  }
};

int main(){
  
  std::cout << std::endl;
    
  showMe(5.5);          // not showMe<double>(5.5);
  showMe(5);            // not showMe<int>(5);
    
  ShowMe(5.5);          // not ShowMe<double>(5.5);
  ShowMe(5);            // not ShowMe<int>(5);
  
  std::cout << std::endl;
    
}

 

The usage of the function template showMe or the class template ShowMe feels the same. From the user perspective, you don't know that you use a template.

With a current GCC 8.2, the program compiles and runs.

 templateArgumentDeduction

To be more specific template argument deduction should work since GCC 7, Clang 5, and MSVC 19.14. cppreference.com gives you the details to the compiler support.

What's next?

Do you know what a Regular or SemiRegular type is? If not, the next post to template interfaces is just the right one for you. Rule T.46 states: "Require template arguments to be at least Regular or SemiRegular.".

 

 

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, lennonli, Pramod Tikare Muralidhara, and Peter Ware.

 

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

 

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

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 39

Yesterday 8683

Week 8723

Month 175557

All 5472661

Currently are 176 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments