问题
As explained in this answer template instantiation allows reducing compilation times and sizes by not requiring templates to be recompiled for every new type in every new file that uses them.
I'm also excited about how C++20 modules should provide a clean solution to expose templates to external projects and reduce hpp/cpp duplication.
What is the syntax that will allow them to work together?
For example, I expect modules to look a bit like (untested and therefore likely wrong code because I don't have a compiler new enough/not sure it is implemented yet):
helloworld.cpp
export module helloworld;
import <iostream>;
template<class T>
export void hello(T t) {
std::cout << t << std::end;
}
helloworld_impl.cpp
export module helloworld_impl;
import helloworld;
// Explicit instantiation
template class hello<int>;
main.cpp
// How to prevent the full definition from being imported here, which would lead
// hello(1) to instantiate a new `hello<int>` instead of reusing the explicit instantiated
// one from `helloworld_impl.cpp`?
import helloworld;
int main() {
hello(1);
}
and then compilation mentioned at https://quuxplusone.github.io/blog/2019/11/07/modular-hello-world will be along (?)
clang++ -std=c++2a -c helloworld.cpp -Xclang -emit-module-interface -o helloworld.pcm
clang++ -std=c++2a -c -fprebuilt-module-path=. -o helloworld_impl.o helloworld_impl.cpp
clang++ -std=c++2a -fprebuilt-module-path=. -o main.out main.cpp helloworld_impl.o
Ideally, I also want the template definition to be usable on external projects.
I think what I want is a way to import the module, and at import time decide between either:
- use all templates in the module as if they were declarations only (I'll be providing my own instantiations on another file)
- use the templates in the module as if they were definitions
This is basically what I achieve in pre-C++20 at "Remove definitions from included headers but also expose templates an external API" but that setup requires copying the interfaces twice, which seems like something the module system can essentially do for us.
来源:https://stackoverflow.com/questions/61520847/how-to-use-template-explicit-instantiation-with-c20-modules