gpt4 book ai didi

c++ - 仅报告一次错误

转载 作者:行者123 更新时间:2023-12-03 08:53:46 27 4
gpt4 key购买 nike

我正在编写一些处理大量数据的代码。发生错误时,通常会发生多次错误,因此我只报告一次。我遇到的问题是,我想要单独的错误消息。在C中,我将使用带有可变参数的方法,当然,这并不是真正的类型安全,因此我想知道如何在C++中使用类型安全输出实现相同的功能。我知道我可以stringstream并创建单个字符串,但这意味着即使已丢弃它也必须创建完整的错误消息,因为它已经被打印了,并且stringstream也不是十分快。

所以目前我使用这样的代码:

    std::string key = "BT:EMPTY";
if(mErrorReport.find(key) == mErrorReport.end())
{
std::cerr << "ERROR [" << Name<< "] Type is empty! " << std::endl;
mErrorReport.insert(key);
}

std::string key = "UI:"+Unitcode;
if(mErrorReport.find(key) == mErrorReport.end())
{
std::cerr << "ERROR [" << Name<< "] Room with the id " << Unitcode << " doesn't exist! " << std::endl;
mErrorReport.insert(key);
}

...

在C语言中,我会这样编写一个可变参数:
 void ErrorLog(const char *key, int nLogLevel, const char fmt, ...)
{
// Check if this error was already reported before.
if(mErrorLog.find(key) == mErrorLog.end())
{
fprintf(stderr, fmt, ...);
mErrorLog.insert(key);
}
}

因此,我想知道是否有一些类似的最佳实践。

最佳答案

你为什么不只用

void ErrorLog(const std::string& key, const std::string& name, const std::string& what)
{
if (mErrorLog.find(key) == mErrorLog.end())
{
std::cerr << "ERROR[" << name << "]" << what << std::endl;
mErrorLog.insert(key);
}
}

并称它为
ErrorLog("BT:EMPTY", Name, "Type is empty!");
ErrorLog("UI:" + Unitcode, Name, std::string("Room with the id ") + Unitcode + " doesn't exist!");

如果 Name不变,则可以删除该参数,然后将其添加到 std::err调用中。

更新:替代解决方案
class ErrorLogWriter
{
public:

ErrorLogWriter(const std::string& name, const std::string& key, std::set<std::string>& log)
:m_name(name)
, m_key(key)
, m_log(log)
{}

ErrorLogWriter& operator<<(const std::string& msg)
{
if (m_log.find(m_key) == m_log.end())
{
std::cerr << "ERROR[" << m_name << "]" << msg << std::endl;
m_log.insert(m_key);
}
return *this;
}

private:
std::string m_name;
std::string m_key;
std::set<std::string>& m_log;
};

class ErrorLog
{
public:

ErrorLog(const std::string& name, std::set<std::string>& log)
:m_name(name)
,m_log(log)
{}

ErrorLogWriter operator()(const std::string& key)
{
return ErrorLogWriter(m_name, key, m_log);
}

private:
std::string m_name;
std::set<std::string>& m_log;
};

int main()
{
std::string Name = "NAME";
std::string Unitcode = "UNITCODE";
std::set<std::string> mErrorLog;

ErrorLog log(Name, mErrorLog);

log("BT:EMPTY") << "Type is empty!";
log("UI:" + Unitcode) << "Room with the id " << Unitcode << " doesn't exist!";
}

关于c++ - 仅报告一次错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33694874/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com