为什么预处理器会用Borland C 识别枚举值,而不是通过视觉C 识别

why does the preprocessor identifies the enum values with Borland C++ but not with visual C++?

本文关键字:识别 视觉 枚举 处理器 预处理 为什么 Borland      更新时间:2023-10-16

我正在尝试将一个项目从Borland C++迁移到Visual C++

我注意到处理枚举的差异,如本示例所述

文件:test_enum.cpp

    #ifdef  _MSC_VER
        #include <iostream>
    #else
        #include <iostream.h>
    #endif
    #include <conio.h>
    using namespace std;
    enum {
        ENUM_0 =0,
        ENUM_1,
        ENUM_2,
        ENUM_3
        } ;
     int main(int argc, char* argv[])
    {
        #ifdef  _MSC_VER
        cout << "Microsoft Visual compiler detected!" << endl;
        #elif defined(__BORLANDC__)
        cout << "Borland compiler detected!" << endl;
        #elif
        cout << "Other compiler detected!" << endl;
        #endif
        #if ENUM_1 > 0
        cout << "ENUM_1 is well defined at preprocessing time" << endl;
        #else
        cout << "No way to see enum variables at preprocessing time" << endl;
        #endif
        cout << "Type any character to exit..." << endl;
        #ifdef  _MSC_VER
            _getch();
        #else
            getch();
        #endif
        return 0;
    }

在Visual Studio中运行代码提供此输出:

Microsoft Visual compiler detected!
No way to see enum variables at preprocessing time
Type any character to exit...

通过使用Borland,我得到:

Borland Compiler detected!
ENUM_1 is well defined at preprocessing time
Type any character to exit...

我想知道Borland如何识别enum?在visual中可以做同样的事情吗?

旧的,过时的和完全无关的Borland C 编译器具有一些独特的怪癖。其中之一是您可以在预处理器指令中使用C 常数表达式。

#if sizeof -1 > 0
    cout << "It looks like you got lucky today" << endl;
#endif
const int answer = 42;
#if answer == 42
    cout << "Unbelievable" << endl;
#endif

绝对没有机会与任何现代编译器一起工作。

只有在有条件地解析某些东西的情况下,预处理程序指令#IF才有必要如果一个文件有

#define SPECIAL_FLAG 1
void only_available_if_special_flag_set();

然后您可能想要,在另一个文件中

#IF SPECIAL_FLAG_SET
    only_available_if_special_flag_set();
#ENDIF

当然,#IF的最大缺点是它只能读取其他与处理前相关的值。虽然Borland的非常特殊的#IF可以读取编译时恒定值,但实时的#IF不能。


c 17的if constexpr将处理可以解析这两种替代方案的情况,但汇编是有条件的。例如

if constexpr(std::is_same_v<std::string, decltype(foo)>) {
  return foo;
} else {
  std::ostringstream out;
  out << foo;
  return out.str();
}

但是我有一个直觉,您所有的真正的需求是常规的旧if语句。编译器已经能够以编译时恒定序列有条件地编译if语句,因此从性能的角度来看,常规if与非常特殊的Borland #IF或C 17的if constexpr相同。例如,

if (int(ENUM_1) > 0) {
  algorithm_which_depends_on_positive_enum_1();
} else {
  fallback_algorithm_for_negative_enum_1();
}