Templates in Modules
Can you use template classes and functions within C++20 modules?
Yes, you can use template classes and functions within C++20 modules. Templates are a powerful feature of C++ that allows you to write generic and reusable code.
Using them within modules follows similar principles to using them in traditional header files but with some added benefits.
Declaring Templates in Modules
Templates can be declared and exported in module interface files, making them available for use in other parts of the program. Here's an example where we declare a template function in a module:
// Math.cppm
export module Math;
export template<typename T>
T add(T a, T b) {
return a + b;
}
Using Templates from Modules
Once declared and exported, you can import the module and use the template functions or classes as needed. Here's an example where we use the templated function imported from our module:
// main.cpp
import Math;
#include <iostream>
int main() {
std::cout << "Int: " << add(2, 3) << "\n";
std::cout << "Double: " << add(2.5, 3.1) << "\n";
}
Int: 5
Double: 5.6
Template Classes in Modules
Template classes can also be declared and used in modules similarly. Here's an example:
// Container.cppm
export module Container;
export template<typename T>
class Container {
public:
void add(T element) {
elements.push_back(element);
}
T get(int index) const {
return elements[index];
}
private:
std::vector<T> elements;
};
// main.cpp
import Container;
#include <iostream>
int main() {
Container<int> intContainer;
intContainer.add(1);
intContainer.add(2);
std::cout << "First element: "
<< intContainer.get(0);
}
First element: 1
Benefits of Using Templates in Modules
- Encapsulation: Templates within modules benefit from the encapsulation provided by modules. Internal details can be hidden, reducing the risk of name clashes and unintended dependencies.
- Improved Compile Times: Since modules are compiled once and reused, using templates within modules can lead to improved compile times compared to repeatedly parsing template definitions in header files.
- Cleaner Code: Using modules with templates can make code cleaner and more maintainable by clearly separating interface and implementation.
Summary
Templates can be effectively used within C++20 modules for both functions and classes.
This approach leverages the benefits of modules, such as improved encapsulation and compile times, while maintaining the power and flexibility of templates.
C++20 Modules
A detailed overview of C++20 modules - the modern alternative to #include
directives. We cover import
and export
statements, partitions, submodules, how to integrate modules with legacy code, and more.