代码之家  ›  专栏  ›  技术社区  ›  TSG

创建定义编译器变量并调用方法的C++宏

  •  0
  • TSG  · 技术社区  · 2 周前

    我试图在C++中创建一个编译器宏,它将定义一个(编译器)变量,然后调用一个C++方法。例如,如果我在C++代码中有这样的代码:

    TL_CLI_ADD_EXIT_CODE(123,"SOMENAME","Description of code")
    

    我希望编译器将其展开为:

    #define EXITCODE_SOMENAME   123
    addExitCode(123,"SOMENAME","Description of code");
    

    我最接近代码的是:

    // Macro to concatenate EXITCODE_ prefix with the number
    #define TL_CLI_CONCAT_EXITCODE(number) EXITCODE_##number
    
    // Macro to create a new exit code definition
    #define TL_CLI_ADD_EXIT_CODE(c,n,d) \
      #define TL_CLI_CONCAT_EXITCODE(n) c \
      addExitCode(c,\"n\",d);
    

    我想做的事情有可能吗?我似乎在各种错误之间循环,包括“#后面没有宏参数”。有人能指出问题所在吗?

    1 回复  |  直到 2 周前
        1
  •  0
  •   Pepijn Kramer    2 周前

    这是C++,尽量避免使用MACRO。通常有一些constexpr方法是可能的,比如这样:

    #include <string_view>
    #include <vector>
    #include <iostream>
    #include <format>
    
    struct ExitCode
    {
        int code;
        std::string_view name;
        std::string_view description;
    
        // implicit conversion to int (for interop with other API's)
        operator int() const noexcept
        {
            return code;
        }
    };
    
    std::ostream& operator<<(std::ostream& os, const ExitCode& err)
    {
        os << std::format("Error : {}, description = {}", err.name, err.description);
        return os;
    }
    
    //-----------------------------------------------------------------------------
    
    static constexpr ExitCode EXITCODE_SOMENAME{123,"SOMENAME","Description of code"};
    
    // return a ref, all data will be put in by compiler (no dynamic mem alloc)
    const ExitCode& SomeFunction()
    {
        return EXITCODE_SOMENAME;
    }
    
    int main()
    {
        auto& retval = SomeFunction();
        std::cout << retval << "\n";
        return retval; // implicit conversion to int here
    }