我在一个模块中有一个向量类:
// other_library.cpp
module;
#include <iostream>
export module mylibrary.other;
export template<class T> class Vector
{
private:
T x, y;
public:
Vector(T _x, T _y) : x(_x), y(_y) {}
void Write()
{
std::cout << "Vector{" << x << ", " << y << "}\n";
}
};在main内部,我创建了一个向量并打印它的内容:
// main.cpp
import mylibrary.other;
int main()
{
Vector<int> vec(1, 2);
vec.Write();
return 0;
}但是,我得到了意外的打印到终端:Vector{10x55a62f2f100c20x55a62f2f100f
以下是使用的构建命令:
g++-11 -std=c++20 -fmodules-ts -c other_library.cpp
g++-11 -std=c++20 -fmodules-ts -c main.cpp
g++-11 -std=c++20 -fmodules-ts *.o -o app
./app当然,如果我将向量类移到主文件中,打印就会按预期进行。我知道模块支持在某种程度上还处于实验阶段。但我希望像这样简单的东西能正常工作。但也许我做错了什么?
编辑:
一种破解的方法是在导入模块之前手动将iostream包含在主文件的顶部,如下所示:
// main.cpp
#include <iostream>
import mylibrary.other;
int main()
{
Vector<int> vec(1, 2);
vec.Write();
return 0;
}这将正确地打印Vector的内容。但是为什么这是必要的呢?在模块中放入内容的目的是为了避免头部包含的麻烦。
因此,我的问题现在有两个方面。
发布于 2021-09-16 16:15:22
因此,模块似乎仍然存在一些挑战。例如:我不能在Vector.Write成员函数中使用std::endl。
一种解决方案是预编译iostream标准头,这可以像这样完成:
g++-11 -std=c++20 -fmodules-ts -xc++-system-header iostream预编译的模块将存储在gcm.cached/目录中,并且将是连续的gcc命令的隐式搜索路径。
现在,我可以完全避免包含标准头文件,所以库文件现在看起来应该是这样的:
// other_library.cpp
export module mylibrary.other;
import <iostream>;
export template<class T> class Vector
{
private:
T x, y;
public:
Vector(T _x, T _y) : x(_x), y(_y) {}
void Write()
{
std::cout << "Vector{" << x << ", " << y << "}"
<< std::endl;
}
};而且我不需要在主文件中做任何进一步的事情--只需导入我的库模块就足够了。
非常感谢Šimon Tóth在他的article on modules中写下了这一点。
https://stackoverflow.com/questions/69209852
复制相似问题