【问题标题】:"Case must be a string or an integral constant" error?“大小写必须是字符串或整数常量”错误?
【发布时间】:2014-05-03 09:34:05
【问题描述】:

好的,这是我的代码:

//================================================
// Constants
//================================================

const string YAML_STRING    =   "tag:yaml.org,2002:str";
const string YAML_INT       =   "tag:yaml.org,2002:int";
const string YAML_FLOAT     =   "tag:yaml.org,2002:float";
const string YAML_BOOL      =   "tag:yaml.org,2002:bool";

const string YAML_SEQ       =   "tag:yaml.org,2002:seq";
const string YAML_SET       =   "tag:yaml.org,2002:set";

const string YAML_MAP       =   "tag:yaml.org,2002:map";
const string YAML_OMAP      =   "tag:yaml.org,2002:omap";
const string YAML_PAIRS     =   "tag:yaml.org,2002:pairs";

//================================================
// Functions
//================================================

Value parseYAMLNode(Node n)
{
    writeln(n.tag);

    switch (n.tag)
    {
        case YAML_STRING    :   return new Value(n.as!(string));
        case YAML_INT       :   return new Value(n.as!(long));
        case YAML_FLOAT     :   return new Value(n.as!(float));
        case YAML_BOOL      :   return new Value(n.as!(bool));
        default             :
        }

        // more code - omitted
}

一旦我决定将我的 case 字符串声明为 const(它们被重复使用,所以我认为这很实用),它会触发 Case must be a string or an integral constant 错误。

这是为什么呢?如何解决这个问题?

【问题讨论】:

    标签: switch-statement constants d dmd


    【解决方案1】:

    好的,这就是我想出的......

    如果常量声明如下:

    enum YAML_STRING = "...";

    而不是const YAML_STRING = "...";

    效果很好。


    P.S.虽然我还是觉得有点奇怪......

    【讨论】:

    • enum 保证是编译时常量(开关情况需要),而const string 只是运行时常量,immutable 也可以工作,我不确定
    【解决方案2】:

    来自dlang

    枚举声明用于定义一组常量。

    或者,来自Çehreli tutorial

    枚举是允许定义命名常量值的功能。

    const 是一个“类型限定符”,表示一个不能被修改的变量。

    【讨论】:

      猜你喜欢
      • 2022-07-14
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      相关资源
      最近更新 更多