C++20: Further Open Questions to Modules

Contents[Show]

So far, I have written in my last four posts the basics you should know about modules in C++20. Only a few questions to modules are still open. In this post, I address these open questions, such as templates in modules, the linkage of modules, and header units.

 TimelineCpp20

I assume in this post that you know my previous posts to modules. If not, make you comfortable and read the following posts.

Templates and Modules

I often hear the question: How are templates exported by modules? When you instantiate a template, it's definitions must be available. This is the reason that template definitions are hosted in headers. Conceptually, the usage of templates has the following structure.

  • templateSum.h

 

// templateSum.h
  
template <typename T, typename T2> auto sum(T fir, T2 sec) { return fir + sec; }

 

  • sumMain.cpp

 

// sumMain.cpp

#include <templateSum.h>

int main() {

    sum(1, 1.5);
    
}

 

The main-program directly includes the header templateSum.h into the program sumMain.cpp. The call sum(1, 1.5) triggers the so-called template instantiation. In this case, the compiler generates out of the function template sum the function sum, which takes an int and a double. If you want to see this process live, play with the example on C++ Insights

With C++20, templates can and should be in modules. Modules have a unique internal representation that is neither source code nor assembly. This representation is a kind of an abstract syntax tree (AST). Thanks to this AST, the template definition is available during template instantiation.

In the following example, I define the function template sum in the module math.

  • mathModuleTemplate.ixx

 

// mathModuleTemplate.ixx

export module math;    

export namespace math {         

    template <typename T, typename T2>
    auto sum(T fir, T2 sec) { 
        return fir + sec;
    }

}

 

  • clientTemplate.cpp

 

// clientTemplate.cpp

#include <iostream>
import math;

int main() {
    
    std::cout << std::endl;     

    std::cout << "math::sum(2000, 11): " << math::sum(2000, 11) << std::endl;

    std::cout << "math::sum(2013.5, 0.5): " << math::sum(2013.5, 0.5) << std::endl;
 
    std::cout << "math::sum(2017, false): " << math::sum(2017, false) << std::endl;
    
}

The command line to compile the program is not different from the previous one in the post "C++20: Structure Modules". Consequently, I skip it and present the output of the program directly:

clientTemplate

With modules, we get a new kind of linkage:

Module Linkage

So far, C++ supports two kinds of linkage: internal linkage and external linkage.

  • Internal linkage: Names with internal linkage are not accessible outside the translation unit. Internal linkage includes mainly namespace-scope names that are declared static and members of anonymous namespaces.
  • External linkage. Names with external linkage are accessible outside the translation unit. External linkage includes mainly names declared not as static, class types, and their members, variables, and templates.

Modules introduce module linkage:

  • Module linkage: Names within module linkage are only accessible inside the module. Names have module linkage if they don't have internal linkage and they are not exported.

A small variation of the previous module math makes my point. Imagine, I want to return the user of my function template sum additionally, which type the compiler deduces as return type.

  • mathModuleTemplate1.ixx

 

// mathModuleTemplate1.ixx

module;

#include <iostream>
#include <typeinfo>
#include <utility>

export module math;   

template <typename T>                               // (2)  
auto showType(T&& t) {
    return typeid(std::forward<T>(t)).name();
}

export namespace math {                             // (3) 

    template <typename T, typename T2>
    auto sum(T fir, T2 sec) {
        auto res = fir + sec;
        return std::make_pair(res, showType(res));  // (1) 
    }

}

 

Instead of the sum of the numbers, the function template sum returns a std::pair (1) consisting of the sum and a string representation of the type res. I put the function template showType (2) not in the exporting namespace math (3). Consequently, invoking it from outside the module math is not possible. showType uses perfect forwarding to preserve the value categories of the function argument t. The function typeid queries information about the type at run-time (runtime type identification (RTTI)).

  • clientTemplate1.cpp

 

// clientTemplate1.cpp

#include <iostream>
import math;

int main() {
    
    std::cout << std::endl;     
   
    auto [val, message] = math::sum(2000, 11);
    std::cout << "math::sum(2000, 11): " << val << "; type: " << message << std::endl;
    
    auto [val1, message1] =  math::sum(2013.5, 0.5);
    std::cout << "math::sum(2013.5, 0.5): " << val1 << "; type: " << message1 << std::endl;
    
    auto [val2, message2] =  math::sum(2017, false);
    std::cout << "math::sum(2017, false): " << val2 << "; type: " << message2 << std::endl;
    
}

Now, the program displays the value of the summation and a string representation of the automatically deduced type.

clientTemplate1

Neither the GCC compiler nor the Clang compiler supports the next feature, which may become one of the favorite features regarding modules.

Header Units

Header units are a smooth way to transition from headers to modules. You just have to replace the #include directive with a new import directive.

 

#include <vector>      => import <vector>;
#include "myHeader.h"  => import "myHeader.h"; 

 

First, import respects the same lookup rules as include. This means in the case of the quotes ("myHeader.h") that the lookup first searches in the local directory before it continues with the system search path.

Second, this is way more than text replacement. In this case, the compiler generates something module-like out of the import directive and treats the result as if it would be a module. The importing module statement gets all exportable names for the header. The exportable names include macros. Importing these synthesized header units is faster and comparable in speed to precompiled headers.

One Drawback

There is one drawback with header units. Not all headers are importable. Which headers are importable is implementation-defined, but the C++ standard guarantees that all standard library headers are importable headers. The ability to import excludes C headers. They are just wrapped in the std namespace. For example <cstring> is the C++ wrapper for <string.h>. You can easily identify the wrapped C header because the pattern is: xxx.h becomes cxxx.

What's next?

With this post, I completed my story to modules and, in particular, I completed my story to the big four in C++20. Here are all existing and upcoming posts to C++20. With my next post, I have a closer look at the core language features in C++, which are not so prominent such as concepts or modules. I start with the three-way comparison operator.

 

 

Thanks a lot to my Patreon Supporters: Meeting C++, Matt Braun, Roman Postanciuc, Venkata Ramesh Gudpati, 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, Jon Hess, Christian Wittenhorst, Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Lakshman, and Kuchlong Kuchlong.

 

Thanks in particular to: Bitwyre Technologies

 

Thanks in particular to:   crp4

 

Seminars

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

Bookable Seminars (Online)

Standard Seminars 

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

Contact Me

Modernes C++,

RainerGrimmSmall

Tags: modules, C++20

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 9506

Yesterday 13046

Week 30408

Month 170169

All 4620261

Currently are 190 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments