【发布时间】:2021-11-11 12:44:13
【问题描述】:
我在模块中有一个向量类:
// 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 的内容。但为什么这是必要的?将东西放入模块中的目的是避免标题包含的麻烦。
因此,我现在的问题有两个。
【问题讨论】:
-
看来
", "和"}\n"被当作const void*... -
@Jarod42 如果是这样,这应该可以工作
std::cout << "Vector{" << x << "\n";。不幸的是,事实并非如此。我还注意到std::endl在 Write 函数中不可访问。 (这也许比可笑更悲伤) -
作为额外测试,您可以在模块中添加一个调用
vec.Write()的函数。 (我还没有尝试过模块)。 -
@Jarod42 结果相同.. 但好主意!
标签: c++ templates module c++20