gpt4 book ai didi

C 程序中带有默认参数的 C++ 头文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:56 24 4
gpt4 key购买 nike

我有一个 C++ 库,其函数在头文件中声明。我的函数声明包含默认参数。

我想通过 Wolfram Mathematica WSTP 模板编译器 (wscc) 在 Mathematica 中使用这个库。这需要为我的库编写一个 C 接口(interface)。我用过这个pattern

#ifdef __cplusplus
extern "C" {
#endif

double my_function(double x, double abs_error = 1E-3);

#ifdef __cplusplus
}
#endif

以防止在我的库中进行名称修改(使用 C++ 编译)。但是默认参数呢?我不认为它们是标准的 C。从 Wolfram Mathematica WSTP 模板编译器 (wscc),我发现

error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token double abs_error = 1E-3,

我是否必须分别进行 C 和 C++ 声明(本质上是两个头文件)?这是一个常见问题还是与我使用 wscc 有关?也许 wscc 不支持这种语法,尽管它通常是可以接受的?

最佳答案

C does not support default arguments.

因此,我假设您想为您的 C++ 代码保留它们,但您可以接受要求 C 调用者(在您的情况下为 Mathematica)为所有参数传递值。

一种可能的方法是定义一个宏,它在 C++ 中扩展为默认值初始值设定项,但在 C 中什么也没有。它不漂亮,但它有效:

#ifdef __cplusplus
#define DEFAULT_VALUE(x) = x
#else
#define DEFAULT_VALUE(x)
#endif

#ifdef __cplusplus
extern "C" {
#endif

void foo(int x DEFAULT_VALUE(42), void *y DEFAULT_VALUE(nullptr));

// In C, this becomes void foo(int x, void *y);
// In C++, this becomes void foo(int x = 42, void *y = nullptr);

#ifdef __cplusplus
}
#endif

关于C 程序中带有默认参数的 C++ 头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com