TimelineCpp20

C++20: Further Open Questions to Modules

So far, I have written in my last four posts the basics you should know about modules in C++20. Only a few questions about 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 yourself comfortable and read the following posts.

Templates and Modules

I often hear the question: How do modules export templates? When you instantiate a template, its 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 the function sum out of the function template, which takes an int and a double. If you want to see this process live, play with the example on C++ Insights

Rainer D 6 P2 500x500

 

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.

     

    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.

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

    • 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 and external.

    • Internal linkage: Names with internal linkage are not accessible outside the translation unit. The internal linkage includes mainly namespace-scope names declared static and anonymous namespaces members.
    • External linkage. Names with external linkage are accessible outside the translation unit. The external linkage includes 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 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 the 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 must 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”), 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 from the import directive and treats the result as 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 all standard library headers are importable. 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 quickly 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 will 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: 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, Matt Godbolt, and Honey Sukesan.

    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

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    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 *