gpt4 book ai didi

c++ - 添加多个相同类型的 boost::error_infos 到一个 boost::exception

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:12:01 24 4
gpt4 key购买 nike

#include <boost/exception/all.hpp>
#include <iostream>

struct myexception : virtual boost::exception, virtual std::exception {};
typedef boost::error_info<struct tag_info, std::string> info;

void main()
{
try
{
BOOST_THROW_EXCEPTION(myexception()
<< info("1")
<< info("2") );
}
catch(const myexception& e)
{
std::cout << boost::diagnostic_information(e) << std::endl;
}
}

这将输出

[struct tag_info *] = 2

我明白为什么会这样,但宁愿让它输出

[struct tag_info *] = 1
[struct tag_info *] = 2

我当然可以 typedef info作为boost::error_info<struct tag_info, std::vector<std::string> >然后将所有信息累积在 std::vector 中在将其转移到异常之前,但这有两个缺点:
a) 它涉及复制 std::vector
b) 我需要在 throw 之前建立 vector ,即我不能简单地使用移位运算符来添加更多信息。

因此,我现在正在寻找更好的解决方案来添加相同 error_info 的多个信息-类型异常。


编辑:
我试着按照 Josh Kelley 在他下面的评论中建议的那样做并重载 operator << :

#include <boost/exception/all.hpp>
#include <iostream>
#include <vector>

typedef boost::error_info<struct tag_info, std::string> info;
typedef boost::error_info<struct tag_multiple_infos, std::vector<std::string> > multiple_infos;

struct myexception : virtual boost::exception, virtual std::exception
{
myexception& operator<< (const info& rhs)
{
std::vector<std::string>* pinfos = boost::get_error_info<multiple_infos, myexception>(*this);
if (pinfos != NULL)
{
pinfos->push_back(rhs.value());
}
else
{
std::vector<std::string> infos;
infos.push_back(rhs.value());
*this << multiple_infos(infos);
}
return *this;
}
};

std::string to_string(const multiple_infos& info)
{
std::ostringstream oss;
std::for_each(info.value().begin(), info.value().end(),
[&oss](const std::string& str) { oss << str << ' '; });
return oss.str();
}

void main()
{
try
{
BOOST_THROW_EXCEPTION(myexception()
<< info("1")
<< info("2") );
}
catch(const myexception& e)
{
std::cout << boost::diagnostic_information(e) << std::endl;
}
}

那会输出

[struct tag_multiple_infos *] = 1 2

这很好,但我更喜欢 Pyotrs 的回答,因为它对我来说看起来更自然并且需要更少的代码。但是,如果我想添加 info s 跨越多个捕获站点1,那么这个解决方案会更合适,因为我不需要知道我已经添加了多少信息。

1 = 即将信息转移到异常中,抛出它,在其他地方捕获它,将更多信息转移到其中,然后重新抛出。

最佳答案

只需使用两个标签:

struct tag_info1;
struct tag_info2;
typedef boost::error_info<tag_info1, std::string> info1;
typedef boost::error_info<tag_info2, std::string> info2;

像这样使用:

    BOOST_THROW_EXCEPTION(myexception()
<< info1("1")
<< info2("2") );

如果您需要更多信息,请使用模板:

template <unsigned N>
struct tag_info {};

template <unsigned N>
struct Nth {
typedef boost::error_info<tag_info<N>, std::string> info;
};

BOOST_THROW_EXCEPTION(myexception()
<< Nth<1>::info("1")
<< Nth<2>::info("2") );

关于c++ - 添加多个相同类型的 boost::error_infos 到一个 boost::exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12498001/

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