c++ - 将参数从一个函数传递到另一个函数(没有模板)- C++

标签 c++ function

<分区>

问题

在 C++ 中,有没有办法将参数从 “sender” 函数传递到 “receiver” 函数?


期望/理论

void print(const char character) { std::putchar(character); }
void print(char message[], unsigned length) {
    for (unsigned iterator = 0u; iterator ^ length; iterator += 1)
        print(*(message + iterator));
}

void println(...) { print(...); print('\n'); std::fflush(stdout); }

在这个例子中:
println“发送者” 函数并且
print“接收者” 函数。

print 函数接受 println 函数的所有参数,如示例 ... 语法所示。


上下文

我确实知道 C++ 中的模板函数以及它如何纠正前面的示例

void print(const char);
void print(char[], unsigned); // They’ve been defined before already…

template <typename... types>
void println(types... arguments) { print(arguments...); print('\n'); std::fflush(stdout); }

但我想看看是否有另一种方法来解决这个问题——没有相当新的 C++-only 特性即:这个问题是如何在 C 中解决的?

我在 C++ 中以 C 风格 方式(使用 C 特性而非 C++ 特性)进行编码,因为我想知道如何构建C++ 个人特色。

最佳答案

how was this problem solved in C?

在 C 中使用宏。只有 ... 的函数宏并将参数传递给函数:

#define println(...)  do { \
        print(__VA_ARGS__); \
        print('\n'); \
        std::fflush(stdout); \
} while(0)

有一个限制 - 根据 ISO C 标准,不允许在没有任何参数的情况下调用此类函数宏。

在 C 中使用 gcc extension 是很常见的将 ## 预处理器运算符应用于 __VA_ARGS__ 并将其他参数传递给 print 函数,例如 __func____LINE____FILE__ 用于调试目的。像前任。 hereherehere (只是简短的谷歌搜索的一些初步结果)。

#define println(str, ...)  do { \
        print("%s:%d: " str "\n", __FILE__, __LINE__, ##__VA_ARGS__); \
        fflush(stdout); \
} while(0)

关于c++ - 将参数从一个函数传递到另一个函数(没有模板)- C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230382/

相关文章:

c++ - 列出运行时使用的 opengl 扩展

c++ - 如何创建两个模板版本以获取数组开始和结束(使用 T* 和 It)而不重复代码?

python - 无需多次迭代即可从文件中获取数据

c - 在终止程序之前存储值

c++ - 如何实现可以用void实例化的智能指针?

c++ - 如何在 C++ 中分配大型动态数组?

c++ - Linux 共享内存与 C++ : Segmentation Fault

c - 使用 DLL 调用 Modelica 外部 C 函数

javascript - JS中如何让循环在特定时间范围内执行某些操作

c++ - 有没有办法在基类的函数中获取派生类的类型?