C++模块化编程出现以下错误,表示使用模块编程不能通过#include来导入头文件,可以通过import来导入
export module test;
//#include <iostream> 不行
import <iostream>; //可以
export void fun(){
std::cout<<"测试"<<std::endl;
}
#include <iostream> //可以
import <iostream>;使用方法参考
使用模块编程+模板编程
export module test;
template <typename T>
export T add(const T &pt1,const T &pt2){
return pt1+pt2;
}
使用以上代码出现错误3:1: 错误:expected unqualified-id before ‘export’
解释为:第三行开头export之前的不识别,第一行export module test,为C++模块接口函数,第三行为模块函数add,猜测可能是第二行无法与add函数建立模板功能,因为add函数开头有export关键字断开了识别模板,所以是1行和2行为一个模块,3行一个模块,编译器不识别1行和2行组成的模块,所以产生第三行开头export之前的不识别的错误
可修改为C++面向对象的方式,改为第一行为接口函数,第二行为模块类,将add函数封装到类的里面如下图
//add.cpp
export module test_add;
export class test{
public:
template<typename T>
T add(const T&pt1,const T&pt2){
return pt1+pt2;
}
};
编写测试main函数,进行测试
//main.cpp
#include <iostream>
import test_add;
int main(){
test test1;
std::cout<<test1.add(1,2)<<std::endl;
}
编译
g++ -std=c++20 -fmodules-ts add.cpp main.cpp -o add