C 中的运行时条件 typedef [英] Runtime conditional typedef in C

查看:33
本文介绍了C 中的运行时条件 typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题有一个 C++ 版本,但是我使用的是标准 typedef 而不是模板.

I know there is a C++ version of this question, however I'm using standard typedefs not templates.

我编写了一个可以处理 16 位 wav 文件的程序.它通过将每个样本加载到一个短片中来做到这一点.然后程序对short 执行算术运算.

I've written a program that works with 16-bit wav files. It does this by loading each sample into a short. The program then performs arithmetic on the short.

我现在正在修改程序,以便它可以同时使用 16 位和 32 位 wav.我希望做一个有条件的 typedef,即对 16 位使用 short,对 32 位使用 int.但后来我意识到,如果编译器事先不知道变量的类型是什么,它可能不会编译代码.

I'm now modifying the program so it can with with both 16- and 32-bit wavs. I was hoping to do a conditional typedef, i.e. using short for 16-bit and int for 32-bit. But then I realised that the compiler probably would not compile the code if it did not know what the type of a variable is beforehand.

所以我尝试测试以下代码:

So I tried to test out the following code:

#include <stdio.h>

int
main()
{
  int i;
  scanf("%i", &i);

  typedef short test;

  if(i == 1)
    typedef short sample;
  else 
    typedef int sample;

  return 0;
}

并得到以下编译器错误:

And got got the following compiler errors:

dt.c: In function ‘main’:
dt.c:12:5: error: expected expression before ‘typedef’
dt.c:14:5: error: expected expression before ‘typedef’

这是否意味着 C 语言中的运行时条件 typedef 是不可能的?

Does this mean that runtime conditional typedefs in C are not possible?

[开放式问题:]如果没有,你们会如何处理这样的事情?

[Open-ended question:] If not, how would you guys handle something like this?

推荐答案

在编译时必须知道程序中的所有类型.

All types in a program must be known at compile time.

在 C++ 中,您可以使用模板为 shortint 编译代码;在 C 中,您可以使用宏(特别是 X-宏)来执行此操作.

In C++ you could compile your code for short and int using templates; in C you can do this using macros (specifically, X-macros).

将您的计算代码放在一个单独的文件中,例如dt.tmpl.c,然后在dt.c中写:

Put your calculation code in a separate file called e.g. dt.tmpl.c, then in dt.c write:

#define sample int
#include "dt.tmpl.c"

#define sample short
#include "dt.tmpl.c"

您的 dt.tmpl.c 代码然后可以使用 sample 作为预处理器标记来命名类型并粘贴到函数名称中,例如:

Your dt.tmpl.c code can then use sample as a preprocessor token to name types and paste into function names, for example:

#define PASTE(name, type) name ## _ ## type
#define FUNCTION_NAME(name, type) PASTE(name, type)

sample FUNCTION_NAME(my_calculation, sample)(sample i) {
    return i * 2;
}

这将产生两个函数 int my_calculation_int(int i)short my_calculation_short(short i),你可以在其他地方使用它们.

This will result in two functions int my_calculation_int(int i) and short my_calculation_short(short i) which you can then use elsewhere.

这篇关于C 中的运行时条件 typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆