C++ based configuration file reading method, system, electronic device and medium
By defining custom data structures in C++ and using template specialization mechanisms to automatically parse configuration files, the problems of redundancy, type insecurity, and maintenance difficulties in existing configuration file reading are solved, achieving efficient and secure configuration management.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- BEIJING GUODIAN ZHISHEN CONTROL TONGDY
- Filing Date
- 2026-03-02
- Publication Date
- 2026-06-19
AI Technical Summary
Existing C++ configuration file reading methods suffer from code redundancy, type insecurity, lack of unified error handling, and maintenance difficulties, resulting in low development efficiency and difficulty in maintenance.
By using C++ templates and reflection mechanisms, custom data structures are defined and template specialization is used to automatically parse configuration files. A unified function interface is provided to achieve automated parsing of configuration files, including format abstraction, recursive reflection assignment, and unified error handling.
It enables automated reading of configuration files, reduces development costs, ensures type safety, improves debugging efficiency, enhances scalability and maintainability, and balances high performance and ease of use.
Smart Images

Figure CN122240163A_ABST
Abstract
Description
Technical Field
[0001] This application belongs to the field of computer technology, specifically relating to a C++-based configuration file reading method, system, electronic device, and medium. Background Technology
[0002] In C++ software development, applications typically need to manage runtime parameters through configuration files (such as INI, JSON, XML, YAML, etc.). Traditional methods for reading configuration files have the following drawbacks: 1. Code redundancy: Developers need to write a lot of repetitive parsing code for each configuration item. For example, when using libraries such as libxml2 or jsoncpp, it is necessary to manually traverse the DOM tree or objects, extract key-value pairs one by one, and assign them to variables.
[0003] 2. Type unsafety: Values read from configuration files are usually strings and need to be manually converted to target types such as int, double, and bool. This process is prone to errors and lacks compile-time type checking.
[0004] 3. Dispersed error handling: For missing configuration items, format errors, type conversion failures, etc., separate error handling is required at each parsing point, resulting in bloated and inconsistent code.
[0005] 4. Difficult to maintain: When the configuration file structure changes, developers must modify a large amount of parsing code simultaneously, which is easy to overlook and introduce errors.
[0006] 5. Lack of uniformity: Different projects or modules may use different parsing libraries and coding styles, resulting in inconsistent code library styles and increasing team collaboration costs.
[0007] Some existing solutions attempt to simplify operations by encapsulating parsing libraries, but they fail to fundamentally solve the problems of coupling parsing logic with business logic and lack of compile-time support. Summary of the Invention
[0008] To address the aforementioned issues, this application provides a C++-based configuration file reading method, system, electronic device, and medium, aiming to automate, type-safe, and standardize configuration management, thereby overcoming or at least partially overcoming the shortcomings of the prior art.
[0009] Firstly, this application provides a C++-based method for reading configuration files, including: Data structure definition steps: Receive a user-defined custom data structure based on C++ syntax, wherein the member variables of the custom data structure are mapped to configuration items in the configuration file, and metadata containing attribute constraints is configured for the member variables; Automatic registration and reflection steps: Based on C++ templates and template specialization mechanisms, the member variable information of the custom data structure is perceived, and corresponding parsing logic is configured for different data types, including C++ basic types and composite types; The parsing entry provides the following steps: Configure a unified function interface, using the custom data structure as a template parameter, and trigger the automated parsing process of the configuration file through this function interface; Parsing and processing steps: The function interface is used to sequentially complete the detection and loading of the configuration file, format abstraction and adaptation, recursive reflection assignment, verification and default value filling, and unified error handling; Configuration object return steps: Returns a strongly typed instance of the custom data structure for which configuration items have been assigned, allowing users to call it directly.
[0010] Secondly, this application also provides a C++-based configuration file reading system, including: A data structure definition unit is used to receive a user-defined custom data structure based on C++ syntax, wherein the member variables of the custom data structure are mapped to configuration items in a configuration file, and metadata containing attribute constraints is configured for the member variables; An automatic registration and reflection unit is used to perceive the member variable information of the custom data structure based on C++ templates and template specialization mechanisms, and to configure corresponding parsing logic for different data types, including C++ basic types and composite types. The parsing entry point provides a unit for configuring a unified function interface, using the custom data structure as a template parameter, and triggering the automated parsing process of the configuration file through this function interface; The parsing and processing unit is used to sequentially complete the detection and loading of the configuration file, format abstraction and adaptation, recursive reflection assignment, verification and default value filling, and unified error handling through the function interface. The configuration object return unit is used to return a strongly typed instance of the custom data structure that has completed the assignment of configuration items, for users to call directly.
[0011] Thirdly, this application also provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the steps of the above-described C++-based configuration file reading method.
[0012] Fourthly, this application also provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the steps of the C++-based configuration file reading method described above.
[0013] The above-mentioned at least one technical application used in the embodiments of this application can achieve the following beneficial effects: This application leverages C++ templates, reflection, and abstraction adaptation mechanisms to achieve automated reading of configuration files, possessing at least the following technical advantages: First, the declarative development model significantly reduces development costs. Users only need to define custom data structures for mapping configuration items, without having to write boilerplate code such as configuration parsing and type conversion. They can focus on business logic to complete configuration reading. Second, compile-time type checking ensures data security. The framework has built-in parsing logic for different types, eliminating errors such as type mismatch and out-of-bounds values caused by handwritten conversion code. Third, it is highly scalable. Through template specialization, it can quickly adapt to custom types and new format configuration files without refactoring the core logic. Fourth, the unified error handling mechanism can output detailed reports containing the location and cause of errors, greatly improving debugging efficiency; Fifth, it has excellent maintainability; changes to the configuration structure only require modification of the data structure definition, and the parsing code does not need to be adjusted. Sixth, the template-based metaprogramming approach allows core logic to be processed during compilation, resulting in runtime efficiency close to hand-written optimized code, balancing ease of use and high performance. Attached Figure Description
[0014] The accompanying drawings, which are included to provide a further understanding of this application and form part of this application, illustrate exemplary embodiments and are used to explain this application, but do not constitute an undue limitation of this application. In the drawings: Figure 1 A flowchart illustrating a C++-based configuration file reading method according to an embodiment of this application is shown; Figure 2 A flowchart illustrating a specific implementation of recursive reflection assignment according to an embodiment of this application is shown; Figure 3 A screenshot of a visual editing interface for a general algorithm configuration file according to an embodiment of this application is shown; Figure 4 A schematic diagram of the process of loading a module using the C++-based configuration file reading method of this application is shown; Figure 5 A schematic diagram of the structure of a C++-based configuration file reading system according to an embodiment of this application is shown; Figure 6 A schematic diagram of the resulting electronic device according to an embodiment of this application is shown. Detailed Implementation
[0015] To make the objectives, technical claims, and advantages of this application clearer, the technical application of this application will be clearly and completely described below with reference to specific embodiments and corresponding drawings. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of them. Based on the embodiments in this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.
[0016] The main concept of this application lies in separating the configuration file parsing process from the C++ data structure definition process, and utilizing C++ metaprogramming techniques and template specialization mechanisms to implement a declarative configuration reading method. Users only need to select the configuration item name, and the system can automatically complete the searching, parsing, adding, deleting, modifying, and validating of the configuration file. This application aims to solve the problems of redundant parsing code, type insecurity, lack of unified error handling, and difficulty in maintenance in existing technologies, thereby improving the efficiency and reliability of C++ application configuration management.
[0017] Example 1 Figure 1 This illustration shows a flowchart of a C++-based configuration file reading method according to an embodiment of this application. Figure 1 As can be seen, this embodiment includes steps S100 to S500: Data structure definition step S100: Receive a custom data structure defined by the user based on C++ syntax, wherein the member variables of the custom data structure are mapped to configuration items in the configuration file, and configure metadata containing attribute constraints for the member variables.
[0018] The attribute constraints include at least one or more of the following: default value, value range, and mandatory field.
[0019] Users can declare configuration data structures through custom data structures. Specifically, users can define a custom data structure, such as a regular C++ struct. This C++ struct is called a custom data structure, and its member variables represent all configuration items that need to be read from the configuration file. Users can use, but are not limited to, standard annotations or custom macros from C++11 / 14 / 17 to annotate constraints. Constraints can include, but are not limited to, default values, value ranges, whether a field is required, etc.
[0020] Specifically, in some embodiments of this application, the C++ structure at least includes member function declarations for constructor, copy constructor, destructor, and assignment operator overload, and the member variables of the C++ structure include one or more of basic data types, user-defined composite data types, array types, and pointer types. The member variables are mapped one-to-one to the algorithm class configuration items in the configuration file. At the same time, the C++ structure exports identifiers through a predefined macro annotation interface to support cross-module calls.
[0021] More specifically, in some embodiments of this application, the basic data type includes one or more of char, int, uint16, and bool; the custom composite data type is one or more of the user-predefined card type structure, command information structure, shape configuration structure, and parameter template structure; the array type is a fixed-length array based on the custom composite data type; and the pointer type is a pointer to the parameter template structure.
[0022] More specifically, in some embodiments of this application, the member variables of the C++ structure are divided into algorithm basic identifier class, quantity statistics class, nested configuration class and algorithm type identifier class according to business attributes. Among them, the member variables of the algorithm type identifier class are bool type feature markers, which are used to identify the type attributes and functional characteristics of the algorithm.
[0023] The following is an example of C++ struct code:
[0024] Automatic registration and reflection step S200: Based on C++ templates and template specialization mechanism, perceive the member variable information of the custom data structure, configure corresponding parsing logic for different data types, including C++ basic types and composite types.
[0025] By leveraging C++'s template and template specialization mechanisms, all member variables and their type information of this custom data structure can be automatically "aware" at compile time or runtime. A unified template class is specialized to provide parsing logic for each basic type and composite type (std::vector, std::map).
[0026] Specifically, a unified template class can be used to perceive the member variable information of a custom data structure and configure the parsing logic for different data types. For basic C++ types, the corresponding type conversion and assignment parsing logic can be directly configured. For composite types, dedicated logic including recursive traversal parsing can be configured. The specialization process of the template class is completed at compile time or runtime, enabling the system to automatically identify the name, type, and hierarchy of all member variables of the custom data structure and match the corresponding parsing logic.
[0027] The parsing entry provides step S300: Configure a unified function interface, using the custom data structure as a template parameter, and trigger the automated parsing process of the configuration file through the function interface.
[0028] This application enables unified entry point parsing. Specifically, it can provide a unified function interface, such as QTextCodec::setCodecForLocale(codec), which can execute an automated parsing process of the configuration file based on the template parameter ParaTemplate_T.
[0029] Parsing and processing step S400: The function interface is used to sequentially complete the detection and loading of the configuration file, format abstraction and adaptation, recursive reflection assignment, verification and default value filling, and unified error handling.
[0030] The unified function interface described above executes the following steps, including but not limited to: detection and loading S401, format abstraction and adaptation S402, recursive reflection assignment S403, validation and default value filling S404, and unified error handling S405.
[0031] In some embodiments of this application, the configuration file detection and loading S401 includes: searching for and loading the configuration file content in a predefined path list based on the provided file name.
[0032] S402 Format Abstraction and Adaptation: Adapts to different configuration files through an abstract Parser interface. The system automatically selects the appropriate configuration file based on the file extension or user specification.
[0033] In this application, the format abstraction and adaptation of configuration files can be accomplished through an abstract Parser interface, thereby achieving unified parsing and adaptation of multiple configuration file formats. The main idea is to shield the parsing differences between different configuration file formats by defining a unified abstract parsing interface, while providing an automatic format matching mechanism. This mechanism can automatically select the parsing logic that matches the target configuration file based on its extension or user-specified format, enabling seamless parsing and calling of various configuration file formats such as INI, JSON, XML, and YAML. This eliminates the need to write separate parsing and calling code for each format, significantly improving the versatility and scalability of configuration parsing. The following provides a detailed explanation of this implementation.
[0034] The abstract Parser interface is a unified parsing behavior specification implemented using pure virtual classes in C++. This Parser interface only declares the core operation interfaces required during configuration file parsing, including but not limited to basic operations such as opening the configuration file, reading configuration items, closing the configuration file, and traversing nested nodes. It does not involve any specific format parsing implementation logic. All parsing logic corresponding to the required configuration file formats must inherit from this abstract Parser interface and implement all the pure virtual functions declared in the interface, ensuring that parsing classes of different formats adhere to a unified operation standard.
[0035] This abstract design decouples the configuration file parsing behavior from the specific format. Upper-level business code only needs to call the unified methods provided by the abstract Parser interface to complete the configuration parsing operation, without needing to know the underlying parsing implementation details. This achieves the design goal of "one interface adapting to multiple formats." Furthermore, when the system needs to add support for other configuration file formats, only a new parser class that inherits from the abstract Parser interface needs to be added, implementing the corresponding parsing methods in the interface. There is no need to modify the upper-level calling code or the logic of existing parser classes, meeting the system's scalability requirements.
[0036] In some embodiments of this application, the recursive reflection assignment S403 specifically includes traversing each member variable in the aforementioned custom data structure and searching for the corresponding node in the configuration file based on the member variable name. Using the specialized parsing logic in step S200, the values in the configuration file are automatically converted to the target type of the member variables, such as int or std::vector, and recursive parsing of the nested structure is performed.
[0037] Specifically, in some embodiments of this application, the recursive reflection assignment step more specifically includes: obtaining the type information T of the target C++ object; determining whether the type information T is a basic type; if so, finding the specialized parser TypeLoader corresponding to the basic type, reading the original value from the configuration node and performing type conversion, and assigning it to the target object after validity verification; if the type information T is a standard container type, identifying the element type of the container, initializing the target container, traversing the child elements of the configuration node and recursively calling this assignment process, and filling the container with the result; if the type information T is a custom structure type, traversing all member variables of the structure, matching the corresponding child node in the configuration node with the member name as the key, and recursively calling this assignment process for each member and child node; if the type information T cannot be identified, throwing an unknown type exception and terminating the current assignment process; confirming that all branch processing is completed, completing the mapping from the current configuration node to the target C++ object.
[0038] Please refer to Figure 2 , Figure 2This diagram illustrates a flowchart of a specific implementation of recursive reflection assignment according to an embodiment of this application. Through type recognition, branching, and recursive calls, it achieves automatic mapping from configuration file nodes to C++ objects. Figure 2 As can be seen, this embodiment includes: After the process starts, the user input is the current configuration node and the target C++ object.
[0039] Obtain the type information T of the target object.
[0040] Determine if the type information T is a basic type. If it is, such as int, double, string, etc., then find the corresponding TypeLoader parser, read the original value of the configuration node, and use the TypeLoader parser to complete the type conversion.
[0041] The converted value undergoes error checking, i.e., validity verification, such as range and format validation. If the verification passes, the value is directly assigned to the target object, and a success message is returned. This also confirms that the recursive reflection assignment was successful.
[0042] If the type information T is not a basic type, then determine whether the type information T is a standard container. If it is, such as vector, map, etc., then identify the element type E of the container, determine whether the configuration node is numeric or mapping, and clear or initialize the target container.
[0043] Iterate through each child element of the configuration node, recursively call this process for each child element, fill the container with the results, and return success when all elements have been processed. It also confirms that the recursive reflection assignment was successful.
[0044] If the type information T is not a standard container, then determine whether the type information T is a custom structure. If it is, then traverse each member M of the structure and find the corresponding child node in the configuration node using the member name as the key.
[0045] This process is recursively called for each member and child node. After all members have been assigned values, a success message is returned. The recursive reflection assignment is then confirmed to have succeeded.
[0046] If the type information T is not a custom structure, it is confirmed that the type information cannot be recognized, and an "Unknown type error" exception is thrown directly, terminating the current process.
[0047] This implementation automates the mapping of configuration data from files to program data structures, eliminating the need for developers to manually write assignment and type conversion code, thus significantly reducing boilerplate code. It relies on compile-time type checking to ensure type safety and avoid manual conversion errors. At the same time, the parsing logic does not need to be adjusted when the data structure changes, improving code maintainability and making configuration parsing more adaptable, supporting the parsing of various basic types and complex nested types.
[0048] In some embodiments of this application, the verification and default value filling S404 includes: during the parsing process, if a configuration item does not exist in the configuration file, then the default value initialized in the custom data structure using the member variable is used. If the value of the configuration item violates the constraints defined in the annotation, such as being out of range, then an explicit exception is thrown.
[0049] This application performs configuration item validity verification and default value filling operations simultaneously during configuration file parsing to ensure the integrity and validity of configuration data. During parsing, the system checks the configuration item matching results for each member variable. If no corresponding configuration item is found in the configuration file, without manual intervention, the system will directly call the pre-initialized default value of that member variable in the custom data structure to complete the assignment, ensuring that there are no uninitialized members in the data structure and guaranteeing the integrity of configuration parsing.
[0050] If a corresponding configuration item exists in the configuration file, but its value violates the constraints marked by the user in the data structure through annotations or custom macros, such as the value exceeding the preset value range or a non-required field having no valid content, the system will immediately trigger the exception mechanism, throwing an exception containing clear information such as the error location, the type of violation constraint, and the actual value, and will not perform the assignment operation to prevent illegal data from entering the program.
[0051] The verification and default value filling steps make configuration parsing both fault-tolerant and rigorous. Default value filling avoids program runtime exceptions caused by missing configuration items, while precise exception throwing can quickly locate errors in the configuration file and improve debugging efficiency.
[0052] In some embodiments of this application, a unified error handling S405 is implemented: any errors encountered during the entire configuration file reading process, such as file not found, missing keys with no default value, type conversion failure, validation failure, etc., will be captured and encapsulated into an exception containing detailed context information, and uniformly thrown upwards.
[0053] Configuration object return step S500: Returns a strongly typed instance of the custom data structure for which configuration items have been assigned, for direct use by the user.
[0054] Upon successful parsing, a fully populated C++ object of type ParaTemplate_T is returned. Users can directly use these configuration values in an object-oriented manner, enjoying full compile-time type checking.
[0055] Example 2 Please refer to Figure 3 , Figure 3 The screenshot shows a visual editing interface for a general algorithm configuration file according to one embodiment of this application. Figure 3 It can be seen that: Figure 3 This document presents the actual storage structure, core configuration items, and interactive operation entry points of the configuration file in this application in a clear and intuitive way, reflecting the actual application scenario of this application.
[0056] from Figure 3 As can be seen, the interface is divided into a "General Information Area" and a "Detailed Configuration Area" according to function. All configuration items are mapped to member variables of the AlgTemplate_T structure, corresponding to specific nodes in the configuration file. General Information Area (Top): Displays the basic identifier configuration of the algorithms, including the total number of algorithms (All Algs: 645), the algorithm ID of the current file (Alg ID: 295), the algorithm name (Alg Name: motor), the card type (CardStyle: Pseudo Card), the algorithm description (Alg Desc: In-line / Without Holding - Pump - Fan - Motor Algorithm), and quantity statistics such as the number of channels (Channel Num: 0), the number of constants (Const Num: 4), and the number of variables (Var Num: 28), which directly correspond to the member variables such as AlgName, Description, CardStyle, and ChannelNum of AlgTemplate_T.
[0057] The detailed configuration area ("Shapes and Cmds" in the middle) is divided into two parts: "Constant Configuration (Const / No)" and "Variable Configuration (Var / No)". It is the core parameter configuration of the algorithm. The constant configuration includes four constants, such as request pulse width (ReqPulseWidth) and startfaildelay. Each constant is marked with constraints such as data type (e.g., F32, U8), upper and lower limits of value (Upper / Lower), initial value (Initial Value), and valid range (ValidRange). It corresponds to the CmdList (command list) member of AlgTemplate_T. Its constraints are consistent with the value range and default value defined in the structure annotation. Variable configuration: Includes 12 variables such as Stop command (StopCmd), Auto start (AutoCmd), and Manual start (Pk1LineIn), labeled with attributes such as variable type (DP / GP), whether it is input (IsInput), and whether a callback is needed (Need Callback), corresponding to the nested configuration class members of AlgTemplate_T, reflecting the hierarchical structure of composite types.
[0058] The bottom and top of the interface provide configuration file operation functions, supporting CRUD operations (creating, deleting, modifying, and querying configurations). File operations include: Save Change, New File, Delete File, and Export, corresponding to the loading and storage process of configuration files. Algorithm operations include: Add Alg, Delete Alg, and Reload, supporting dynamic adjustment of configuration items and providing flexibility in configuration parsing.
[0059] Example 3 Please refer to Figure 4 , Figure 4 This diagram illustrates the process of loading a module using the C++-based configuration file reading method described in this application. Figure 4 As can be seen, this embodiment includes the following steps: It begins as the process trigger node.
[0060] Then the step proceeds to reading the INI configuration file, the purpose of which is to load the target INI format configuration file.
[0061] The structured parsing of files is accomplished by relying on a parsing library, specifically using the mini library to parse the INI file structure.
[0062] Retrieve module names from SECTION or specific keys, such as extracting the names of algorithm or functional modules from the SECTION node of an INI.
[0063] The description within the module is read from the description key (KEY), which can be understood as the configuration item key value within the module.
[0064] Count the number of configuration items for constants and variables in the module, specifically the number of constants Nc and the number of variables Nv.
[0065] Memory space is allocated based on the statistical quantity. Specifically, the module memory is dynamically allocated, and its size is the constant Ncsizeof plus the variable Nvsizeof.
[0066] The process enters two branches: one looping through each variable and the other looping through each constant. The constant processing branch and the variable processing branch can be executed in parallel or sequentially; the following explanation uses sequential execution as an example.
[0067] First, enter the constant processing branch and read the constant attributes, which include but are not limited to name, description, data type, and configuration type. Then, validate the data type and configuration type: if the validation fails, record the error and use a safe default value; if the validation passes, write the constant data into memory.
[0068] Then, the program enters the variable processing branch, reads the variable attributes, which include, but are not limited to, name, description, data type, and configuration type. It validates the data type and configuration type; if validation fails, the error is recorded and the process is skipped; if validation passes, the variable data is written to memory. Then, it moves on to the next variable, and so on, until all variables have been processed, at which point the module initialization is confirmed to be complete.
[0069] Example 4 The application of this embodiment will be explained by taking loading a module as an example: 1. The program calls addTemplDlg.getNewPara(&name,&desc); `fullName = QString("%1 / Algtemplate_%2.ini").arg(QString(m_EtcPath)).arg(name)` reads the configuration file information. 2. The program iterates through the module type numbers and their names in the specified template file (full path).
[0070] 3. AppConfig begins parsing the AlgTemplate_T type. It creates an empty AppConfig object.
[0071] 4. For each member of AppConfig: For example, in the nmotor database, find the key "NMOTOR" with the value "295". Since nmotor is of type std::string, simply assign the value "295". B iterates to the configuration item NMOTOR and reads the NMOTOR constant variable information; C parses information about constant variables, including their description, data type, and default value.
[0072] After all members have been parsed, the queried module object is returned. Users can then visualize the configuration file information. Below is a demonstration of some key code snippets:
[0073] In summary, this application achieves automated reading of configuration files by relying on C++ templates, reflection, and abstract adaptation mechanisms, and possesses at least the following technical advantages: First, the declarative development model significantly reduces development costs. Users only need to define custom data structures for mapping configuration items, without having to write boilerplate code such as configuration parsing and type conversion. They can focus on business logic to complete configuration reading. Second, compile-time type checking ensures data security. The framework has built-in parsing logic for different types, eliminating errors such as type mismatch and out-of-bounds values caused by handwritten conversion code. Third, it is highly scalable. Through template specialization, it can quickly adapt to custom types and new format configuration files without refactoring the core logic. Fourth, the unified error handling mechanism can output detailed reports containing the location and cause of errors, greatly improving debugging efficiency; Fifth, it has excellent maintainability; changes to the configuration structure only require modification of the data structure definition, and the parsing code does not need to be adjusted. Sixth, the template-based metaprogramming approach allows core logic to be processed during compilation, resulting in runtime efficiency close to hand-written optimized code, balancing ease of use and high performance.
[0074] Figure 5 This diagram illustrates the structure of a C++-based configuration file reading system according to an embodiment of this application. Figure 5 As can be seen, the C++-based configuration file reading system 500 includes: The data structure definition unit 510 is used to receive a custom data structure defined by the user based on C++ syntax, wherein the member variables of the custom data structure are mapped to configuration items in the configuration file, and the member variables are configured with metadata containing attribute constraints. The automatic registration and reflection unit 520 is used to perceive the member variable information of the custom data structure based on C++ templates and template specialization mechanisms, and to configure corresponding parsing logic for different data types, including C++ basic types and composite types. The parsing entry provides unit 530, which is used to configure a unified function interface, using the custom data structure as template parameters, and triggers the automatic parsing process of the configuration file through the function interface; The parsing and processing unit 540 is used to sequentially complete the detection and loading of the configuration file, format abstraction and adaptation, recursive reflection assignment, verification and default value filling, and unified error handling through the function interface. Configuration object return unit 550 is used to return a strongly typed instance of the custom data structure that has completed the assignment of configuration items, for users to call directly.
[0075] It should be noted that the system can implement the aforementioned C++-based configuration file reading methods one by one. The implementation details will not be elaborated here.
[0076] Figure 6 This invention illustrates a schematic diagram of the structure of an electronic device according to an embodiment of the present application. Figure 6 As shown, the electronic device includes a processor, memory, network interface, and database connected via a system bus. The processor provides computing and control capabilities. The memory includes non-volatile and / or volatile storage media and internal memory. The non-volatile storage media stores the operating system, computer programs, and database. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used for communication with external devices via a network connection. When executed by the processor, the computer program implements the functions or steps of a C++-based configuration file reading method.
[0077] In one embodiment, the electronic device provided in this application includes a memory and a processor. The memory stores a database and a computer program that can run on the processor. When the processor executes the computer program, it implements the steps of the aforementioned C++-based configuration file reading method.
[0078] The above is as stated in this application. Figure 5The C++-based configuration file reading system execution method disclosed in the illustrated embodiments can be applied to a processor or implemented by a processor. During implementation, each step of the above method can be completed by integrated logic circuits in the processor's hardware or by software instructions. The processor can be a general-purpose processor, including a Central Processing Unit (CPU), a Network Processor (NP), etc.; it can also be a Digital Signal Processor (DSP), an Application Specific Integrated Circuit (ASIC), a Field-Programmable Gate Array (FPGA), or other programmable logic devices, discrete gate or transistor logic devices, or discrete hardware components. The steps of the method disclosed in the embodiments of this application can be directly embodied as being executed by a hardware decoding processor, or executed by a combination of hardware and software modules in the decoding processor. The software modules can reside in random access memory, flash memory, read-only memory, programmable read-only memory, electrically erasable programmable memory, registers, or other mature storage media in the art. This storage medium is located in memory, and the processor reads information from the memory and, in conjunction with its hardware, completes the steps of the above method.
[0079] In one embodiment, a computer-readable storage medium is also provided, on which a computer program is stored, which, when executed by a processor, implements the steps of the aforementioned C++-based configuration file reading method.
[0080] It should be noted that the functions or steps that the above-mentioned electronic devices or computer-readable storage media can achieve can be referred to the relevant descriptions in the foregoing method embodiments. To avoid repetition, they will not be described one by one here.
[0081] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program can be stored in a non-volatile computer-readable storage medium. When executed, the computer program can include the processes of the embodiments of the above methods. Any references to memory, storage, databases, or other media used in the embodiments provided in this application can include non-volatile and / or volatile memory. Non-volatile memory may include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM), or flash memory. Volatile memory may include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM is available in a variety of forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), dual data rate SDRAM (DDRSDRAM), enhanced SDRAM (ESDRAM), synchronous link DRAM (SLDRAM), RAMbus direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM), etc.
[0082] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the above-described division of functional units and modules is used as an example. In practical applications, the above functions can be assigned to different functional units and modules as needed, that is, the internal structure of the system can be divided into different functional units or modules to complete all or part of the functions described above.
[0083] The above-described embodiments are only used to illustrate the technical application of this application, and are not intended to limit it. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical applications described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical applications to deviate from the spirit and scope of the technical applications of the embodiments of this application, and should all be included within the protection scope of this application.
Claims
1. A C++-based method for reading configuration files, characterized in that, include: Data structure definition steps: Receive a user-defined custom data structure based on C++ syntax, wherein the member variables of the custom data structure are mapped to configuration items in the configuration file, and metadata containing attribute constraints is configured for the member variables; Automatic registration and reflection steps: Based on C++ templates and template specialization mechanisms, the member variable information of the custom data structure is perceived, and corresponding parsing logic is configured for different data types, including C++ basic types and composite types; The parsing entry provides the following steps: Configure a unified function interface, using the custom data structure as a template parameter, and trigger the automated parsing process of the configuration file through this function interface; Parsing and processing steps: The function interface is used to sequentially complete the detection and loading of the configuration file, format abstraction and adaptation, recursive reflection assignment, verification and default value filling, and unified error handling; Configuration object return steps: Returns a strongly typed instance of the custom data structure for which configuration items have been assigned, allowing users to call it directly.
2. The method according to claim 1, characterized in that, The custom data structure is a C++ structure. The C++ structure contains member function declarations for constructors, copy constructors, destructors, and assignment operator overloads. The member variables of the C++ structure contain one or more of the following: basic data types, custom composite data types, array types, and pointer types. The member variables are mapped one-to-one to the algorithm class configuration items in the configuration file. The C++ structure exports identifiers through a predefined macro annotation interface to support cross-module calls.
3. The method according to claim 2, characterized in that, The basic data types include one or more of char, int, uint16, and bool; The custom composite data type is one or more of the following predefined by the user: card type structure, command information structure, shape configuration structure, and parameter template structure; The array type is a fixed-length array based on a custom composite data type, and the pointer type is a pointer to a parameter template structure.
4. The method according to claim 1, characterized in that, In the parsing and processing steps, the detection and loading of the configuration file includes: searching for and loading the configuration file content in a predefined path list based on the file name provided by the user; Format abstraction and adaptation include: adapting to different configuration files through an abstract Parser interface, wherein the Parser interface enables parsing classes of different formats to follow a unified operating standard; Recursive reflection assignment specifically includes: traversing each member variable in the custom data structure, finding the corresponding node in the configuration file based on the member variable name; using specialized parsing logic, automatically converting the value in the configuration file into the target type of the member variable, and performing recursive parsing of the nested structure.
5. The method according to claim 1, characterized in that, Validation and default value population specifically include: during the parsing process, if a configuration item does not exist in the configuration file, the default value initialized in the custom data structure using that member variable is used; if the value of a configuration item violates the constraints defined in the annotation, an explicit exception is thrown. The unified error handling specifically includes: any error encountered during the entire configuration file reading process, such as file not found, missing key and no default value, type conversion failure, or validation failure, will be captured and encapsulated into an exception containing detailed context information, and uniformly thrown upwards.
6. The method according to claim 4, characterized in that, More specifically, recursive reflection assignment includes: Obtain the type information T of the target C++ object; Determine if the type information T is a basic type. If so, find the corresponding specialization parser TypeLoader for the basic type, read the original value from the configuration node and perform type conversion. After validity verification, assign the value to the target object. If the type information T is a standard container type, then identify the element type of the container, initialize the target container, traverse the child elements of the configuration node and recursively call this assignment process, and fill the container with the result; If the type information T is a custom structure type, then iterate through all member variables of the structure, match the corresponding child nodes in the configuration node with the member name as the key, and recursively call this assignment process for each member and child node. If the type information T cannot be identified, an unknown type exception is thrown, terminating the current assignment process; After confirming that all objects have been processed, complete the mapping from the current configuration node to the target C++ object.
7. A configuration file reading system based on C++, characterized in that, include: A data structure definition unit is used to receive a user-defined custom data structure based on C++ syntax, wherein the member variables of the custom data structure are mapped to configuration items in a configuration file, and metadata containing attribute constraints is configured for the member variables; An automatic registration and reflection unit is used to perceive the member variable information of the custom data structure based on C++ templates and template specialization mechanisms, and to configure corresponding parsing logic for different data types, including C++ basic types and composite types. The parsing entry point provides a unit for configuring a unified function interface, using the custom data structure as a template parameter, and triggering the automated parsing process of the configuration file through this function interface; The parsing and processing unit is used to sequentially complete the detection and loading of the configuration file, format abstraction and adaptation, recursive reflection assignment, verification and default value filling, and unified error handling through the function interface. The configuration object return unit is used to return a strongly typed instance of the custom data structure that has completed the assignment of configuration items, for users to call directly.
8. The configuration file reading system based on C++ according to claim 1, characterized in that, The system also includes: A configuration file visual editing interface is provided on the user side, which is connected to the data structure definition unit and is used to receive user-defined information and transmit it to the data structure definition unit.
9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes a computer program, it implements the steps of the C++-based configuration file reading method as described in any one of claims 1 to 6.
10. A computer-readable storage medium storing a computer program, characterized in that, When a computer program is executed by a processor, it implements the steps of the C++-based configuration file reading method as described in any one of claims 1 to 6.