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.
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;
}
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 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
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.
Answers to questions are automatically generated and may not have been reviewed.
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.