C++20模块化编程,错误:expected unqualified-id before ‘export’,错误:post-module-declaration imports must not be

C++模块化编程出现以下错误,表示使用模块编程不能通过#include来导入头文件,可以通过import来导入

export module test;
//#include <iostream> 不行
import  <iostream>;  //可以
export  void  fun(){
std::cout<<"测试"<<std::endl;
}
#include <iostream>  //可以

import  <iostream>;使用方法参考

C++20使用import

使用模块编程+模板编程

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值