【问题标题】:C++ How to correctly print value of templated type from moduleC ++如何从模块中正确打印模板类型的值
【发布时间】: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 &lt;&lt; "Vector{" &lt;&lt; x &lt;&lt; "\n";。不幸的是,事实并非如此。我还注意到 std::endl 在 Write 函数中不可访问。 (这也许比可笑更悲伤)
  • 作为额外测试,您可以在模块中添加一个调用vec.Write() 的函数。 (我还没有尝试过模块)。
  • @Jarod42 结果相同.. 但好主意!

标签: c++ templates module c++20


【解决方案1】:

因此,模块似乎仍然存在一些挑战。示例:我不能在Vector.Write 成员函数中使用std::endl

一个解决方案是预编译iostream标准头,可以这样完成:

g++-11 -std=c++20 -fmodules-ts -xc++-system-header iostream

预编译的模块会存放在 gcm.cached/ 目录下,是连续 gcc-commands 的隐式搜索路径。

现在,我可以完全避免包含标准头文件,所以库文件现在看起来像这样:

// 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 中写到这个。

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 2017-09-22
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2015-08-03
    相关资源
    最近更新 更多