在 C++20 中混合模块和头文件是否可能/可接受?

inf*_*ero 6 c++ c++20 c++-modules

我实际上是在尝试通过编写自己的小模块来理解 C++20 模块系统。假设我想提供一个函数来删除字符串开头和结尾的所有空格(一个trim函数)。下面的代码工作没有问题

module;

export module String;

import std.core;

export std::string delete_all_spaces(std::string const & string)
{
    std::string copy { string };

    auto first_non_space { std::find_if_not(std::begin(copy), std::end(copy), isspace) };
    copy.erase(std::begin(copy), first_non_space);

    std::reverse(std::begin(copy), std::end(copy));
    first_non_space = std::find_if_not(std::begin(copy), std::end(copy), isspace);
    copy.erase(std::begin(copy), first_non_space);
    std::reverse(std::begin(copy), std::end(copy));

    return copy;
}
Run Code Online (Sandbox Code Playgroud)
import std.core;
import String;

int main()
{
    std::cout << delete_all_spaces("  Hello World!    \n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是如果我只想使用特定的头文件而不是std.core在我的模块中呢?如果这样做,将 替换为import std.core以下代码,我会在 Visual Studio 2019 上收到错误消息。

module;

#include <algorithm>
#include <cctype>
#include <string>

export module String;

// No more import of std.core

export std::string delete_all_spaces(std::string const & string)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)
Error LNK1179 file not valid or damaged: '??$_Deallocate@$07$0A@@std@@YAXPAXI@Z' COMDAT duplicated
Run Code Online (Sandbox Code Playgroud)

但是,如果在main.cppI 替换以及import std.corewith 中#include <iostream>,代码将再次编译。这就像使用两个系统证明链接器完成它的工作一样

问题是:我做错了吗?同时使用新方法import和旧#include方法是一种不好的做法吗?我在 Internet 上的多篇文章中看到,您可以在模块中包含一些旧的标头,从而在不破坏现有代码的情况下现代化您的代码。但是,如果此标头包含 STL 的某些部分,例如#include <string>但我的模块使用了import std.core怎么办?

我仅使用 Visual Studio 2019 进行测试,因为到目前为止,import std.core它不适用于 GCC。那么,它可能来自 VS 中的错误吗?还是所有编译器的问题都一样?

ic_*_*eer 3

是的,模块可以与头文件一起使用。我们可以在同一个文件中导入和包含标头,这是一个示例:

import <iostream>
#include <vector>
int main()
{
  std::vector<int> v{1,6,8,7};
  for (auto i:v)
    std::cout<<i;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

创建模块时,您可以自由导出模块接口文件中的实体并将实现移动到其他文件。总之,逻辑与管理 .h 和 .cpp 文件相同

  • 使用 VS Studio 16.9.1,问题似乎得到了解决,因为问题中的代码(与“import std.core”和 C-includes 混合)以前有问题,现在可以编译。但“import &lt;header&gt;”仍然不起作用。 (2认同)