Go教程

c++仿照go语言的error,函数返回值封装

本文主要是介绍c++仿照go语言的error,函数返回值封装,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

c++仿照go语言,程序返回错误时,可以附加错误信息

#ifndef __ERRORMSG_H_
#define __ERRORMSG_H_
#include <string>
struct Errormsg
{
    typedef enum
    {
        OK = 0,
        ERR = 1,
    } HerrorCode;
    HerrorCode code = OK;
    std::string desc = "";
    int line;
    std::string file;
    Errormsg() {}
    Errormsg(HerrorCode c)
    {
        code = c;
    }
    Errormsg(HerrorCode c, const char *d)
    {
        code = c;
        desc = d;
    }
    Errormsg(HerrorCode c, std::string d)
    {
        code = c;
        desc = d;
    }
    Errormsg(HerrorCode c, std::string d, const char *_file, int _line)
    {
        code = c;
        file = _file;
        line = _line;
        desc = d;
    }
    std::string flDesc()
    {
        return std::string("[") + file + "#" + std::to_string(line) + "]" + desc;
    }
    ~Errormsg() {}
    bool isOk() { return code == OK; }
};

#define ERRORSMSG_OK Errormsg(Errormsg::ERR, "ok")
#define ERRORSMSG_ERR(str) Errormsg(Errormsg::ERR, str)
#define ERRORSMSG_ERR_FL(str) Errormsg(Errormsg::ERR, str, __FILE__, __LINE__)

#endif

使用示例:

int main(int argc, char const *argv[])
{
    Errormsg e = ERRORSMSG_OK;
    printf("msg, %s\n", e.desc.c_str());

    e = ERRORSMSG_ERR("run err");
    printf("msg, %s\n", e.desc.c_str());

    e = ERRORSMSG_ERR_FL("run err msg");
    if (e.isOk()){
        printf("run ok\n");
    }
    else{
        printf("run err, file:%s, line:%d, msg: %s\n", e.file.c_str(), e.line, e.desc.c_str());
        printf("run err, %s\n", e.flDesc().c_str());
    }
    return 0;
}

输出结果

msg, ok
msg, run err
run err, file:a.cpp, line:59, msg: run err msg
run err, [a.cpp#59]run err msg

更多编程资料见公众号 xutopia77

这篇关于c++仿照go语言的error,函数返回值封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!