如何使用C++模块:带有模板的私有片段



我正在试用C++20,以更好地了解它们在实践中的工作方式。我了解了module :private片段,该片段可用于将接口与实现分离,同时将两者保存在同一文件中。这似乎适用于标准函数,但不适用于模板函数。

我有以下文件:

// File "main.cpp"
#include <iostream>
import mymodule;
int main()
{
std::cout << "greeting(): " << mymodule::greetings() << std::endl;
int x = 1;
int y = 2;
std::cout << "add(x, y): " << mymodule::add(x, y) << std::endl;
}
// File "mymodule.ixx"
module;
#include <string>
// declare interface
export module mymodule;
export namespace mymodule {
template<typename T>
T add(T x, T y);
std::string greetings();
}
// implement interface
module :private;
std::string mymodule::greetings() {
return "hello";
}
template<typename T>
T mymodule::add(T x, T y) {
return x + y;
}

并获得编译器警告和链接器错误(使用Visual Studio 2022,MSVC(:

Rebuild started...
1>------ Rebuild All started: Project: PlayingWithModules, Configuration: Debug x64 ------
1>Scanning sources for module dependencies...
1>mymodule.ixx
1>Compiling...
1>mymodule.ixx
1>C:UsersSamDevelopmentCppSandboxPlayingWithModulesmymodule.ixx(29,13): warning C5226: 'mymodule::add': exported template defined in private module fragment has no reachable instantiation
1>main.cpp
1>main.obj : error LNK2019: unresolved external symbol "int __cdecl mymodule::add<int>(int,int)" (??$add@H@mymodule@@YAHHH@Z::<!mymodule>) referenced in function main
1>C:UsersSamDevelopmentCppSandboxx64DebugPlayingWithModules.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "PlayingWithModules.vcxproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

我的理解是mymodule::greetings()是可以的,但mymodule::add(x, y)不是,因为编译器看不到函数调用mymodule::<int, int>(x, y),这导致没有生成函数<int, int>


如果我将模板功能作为接口的一部分来实现:

module;
#include <string>
// declare interface
export module mymodule;
export namespace mymodule {
template<typename T>
T add(T x, T y) {
return x + y;
}
std::string greetings();
}
// implement interface
module :private;
std::string mymodule::greetings() {
return "hello";
}

然后一切都按预期编译并运行。


是否可以将module :private与功能模板一起使用,如果可以,如何使用?还是模板函数应该始终作为接口的一部分来实现?我在模块上下文中找不到有关模板使用的详细信息,也找不到对编译器警告的引用。

模块不会改变C++的特性,只是改变访问不同组件的方式。

C++的本质是,为了让翻译单元使用模板,该翻译单元必须能够访问该模板的定义。模块不会改变这一点。

私有模块片段专门包含模块接口的而非部分。这就是它们的全部意义:能够将不属于接口的东西粘贴到模块文件中。

因此,私有模块片段只能包含要放入传统.cpp文件中的内容。事实上,这就是它们存在的原因:这样(对于短模块(您就可以将所有常见的.cpp内容放在一个文件中,而不会影响模块生成的内容。

最新更新