c++ - C ++如何从模块中正确打印模板类型的值
问题描述
我在模块中有一个向量类:
// 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 的内容。但为什么这是必要的?将东西放入模块中的目的是避免包含标题的麻烦。
因此,我的问题现在有两个方面。
解决方案
因此,模块似乎仍然存在一些挑战。示例:我不能在成员函数std::endl
内部使用。Vector.Write
一种解决方案是预编译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 在他的关于模块的文章中写到这一点。
推荐阅读
- javascript - 我尝试使用 style.display = "none"; 让Javascript隐藏我的视频标签,但这不起作用?
- java - 相当于 Java 中进程的 ThreadPool
- typescript - 如何从嵌套对象创建字符串文字类型?
- python - 在 django 中添加了两个搜索栏,一个按 id 搜索,另一个按名称搜索。尝试了很多方法,但如果我按 id 尝试则无法做到,那么我无法使用名称
- flutter - AndroidManifest.xml 中有多个未解析的类。使用 shared_intent 插件 MissingPluginException 时出错
- numpy - 如何按列比较二维数组和一维数组?
- swift - 如何使用 SwiftuI 在 Apple Watch 上的初始视图故事板左侧制作故事板?
- pandas - ValueError:无法将字符串转换为浮点数:“A”图
- firebase - 我如何在颤振中从 firebse 实时数据库中检索数据
- angular - 在按钮点击条件下过滤 mat-table