You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Bison C++中使用枚举作为语义类型遇编译错误的技术咨询

Bison C++ 枚举语义类型编译错误解决方案

问题场景

在Bison C++项目中尝试将枚举作为语义类型使用,.y文件中配置了:

%type <order_direction> ordering_direction opt_ordering_direction

order_direction在单独头文件中定义为:

enum enum_order : int { ORDER_NOT_RELEVANT = 1, ORDER_ASC, ORDER_DESC };
enum_order order_direction;

已在Bison文件中引入该头文件,但链接目标文件时出现错误:

error: ‘order_direction’ is not a type
 5091 |       basic_symbol (typename Base::kind_type t, order_direction&& v, location_type&& l)

同时.y文件使用了如下定义:

%define api.token.constructor
%define api.value.type variant
%define parse.assert

问题原因

头文件里把order_direction定义成了变量,而非类型。Bison的%type <xxx>语法要求<>内是合法类型名,但order_direction是enum_order类型的变量实例,并非类型本身,因此编译器报错。

解决步骤

  1. 修改头文件,区分类型与变量:
    // 定义枚举类型
    enum enum_order : int { ORDER_NOT_RELEVANT = 1, ORDER_ASC, ORDER_DESC };
    // 若需全局变量,单独声明(可选)
    // extern enum_order order_direction;
    
  2. 在Bison的.y文件中,将%type的类型参数改为枚举类型名enum_order:
    %type <enum_order> ordering_direction opt_ordering_direction
    
  3. 若确实需要order_direction变量,在对应.cpp文件中定义(避免头文件重复定义问题):
    enum_order order_direction;
    

额外说明

由于启用了%define api.value.type variant,Bison会生成基于std::variant的语义值类型,要求所有指定的语义类型均为合法C++类型,不能是变量名。修正类型名后,Bison可正确生成对应代码,消除编译错误。


内容的提问来源于stack exchange,提问作者Bernie gach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:10:29