【问题标题】:How to save the result of typeof? [closed]如何保存typeof的结果? [关闭]
【发布时间】:2017-07-02 12:29:01
【问题描述】:

我是一名新程序员,主要使用 Code::Blocks for C99。 我最近发现了typeof(),因为它被隐藏为 __typeof __() 我想知道您是否可以将类型保存为 typeof 的结果。类似:

type a = __typeof__(?); 

或者

#define typeof __typeof__
type a = typeof(?);

这可能吗?

【问题讨论】:

  • 标准 C 中没有 typeof 运算符。您必须阅读 compiler(不是 Code::Blocks IDE)的文档以了解更多信息。另外,不要做你想做的事,99.99% 的情况下你不应该做的事。也许如果您解释为什么您想这样做,您想要解决的实际问题是什么,那么我们可以为您提供帮助。
  • 如果var 的类型为int,那么typeof(var) 就是int。你能说type a = int; 或类似的话吗?这意味着什么?你为什么需要这样的东西?
  • 假设你想做一些类似于用 Java 写 Class c = "foo".getClass(); 的东西:算了,它不像 C 语言那样工作。在运行时没有可用的类型信息。

标签: c c99 typeof


【解决方案1】:

您应该避免使用 typeof__typeof __(),因为它们不是标准 C。最新的 C 版本 (C11) 通过 _Generic 关键字支持这一点,其工作方式相同。

C 中没有“类型类型”,但您可以轻松地自己制作:

typedef enum
{
  TYPE_INT,
  TYPE_FLOAT,
  TYPE_CHAR
} type_t;

#define get_typeof(x)   \
  _Generic((x),         \
    int:   TYPE_INT,    \
    float: TYPE_FLOAT,  \
    char:  TYPE_CHAR );

...

float f;
type_t type = get_typeof(f);

【讨论】:

    【解决方案2】:

    不,您不能像 t = (typeof(x) == int) ? a : b;int t = typeof(x); 一样使用 typeof

    如果你是 C11 以下,_Generic 可以帮助:

    #include <stdio.h>
    
    enum {TYPE_UNKNOWN, TYPE_INT, TYPE_CHAR, TYPE_DOUBLE};
    
    #define type_of(T) _Generic((T), int: TYPE_INT, char: TYPE_CHAR, double: TYPE_DOUBLE, default: 0)
    
    int main(void)
    {
        double a = 5.;
        int t = type_of(a);
    
        switch (t) {
            case TYPE_INT:
                puts("a is int");
                break;
            case TYPE_CHAR:
                puts("a is char");
                break;
            case TYPE_DOUBLE:
                puts("a is double");
                break;
            default:
                puts("a is unknown");
                break;
        }
        return 0;
    }
    

    【讨论】:

    • 谢谢!我将编译器更改为 c11 并使用了“_Generic”。
    猜你喜欢
    • 2015-03-26
    • 2013-04-13
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    相关资源
    最近更新 更多