gpt4 book ai didi

c++ - 非确定性操作的设计模式(nondet.factory?)

转载 作者:行者123 更新时间:2023-11-28 02:05:08 25 4
gpt4 key购买 nike

假设我有这个重复出现的代码块:

Class1 c1;
try {
c1.parse(x);
} catch(Exception& e) {
Class2 c2;
try {
c2.parse(x);
} catch(Exception& e) {
Class3 c3;
try {
// ...
}
// ...
}
}

显然,我感兴趣的是第一个 Class# (#=1,2,3,...) 解析不会抛出异常的实例。

可选地,Class1, ..., ClassN 有一个公共(public)父类(super class),我可以将它用作返回类型。

什么是简洁抽象此操作的方法,考虑到它会在代码中多次出现?

可以用STL和Boost,不能用C++11,因为项目需要:(宏是一个灰色地带。

最佳答案

没有可变参数,并且仅限于 c++03,我们被迫按照 boost 库的方式来做 - 前面有很多样板以换取稍后方便的表达:

#include <string>
#include <stdexcept>

struct Class1 { void parse(const std::string&); };
struct Class2 { void parse(const std::string&); };
struct Class3 { void parse(const std::string&); };

struct none_type {};

template<class C>
struct try_impl
{
try_impl(int index)
: _index(index)
{
}
void apply(int& which, C& c, const std::string& s) const
{
if (which >= 0)
return;
try {
c.parse(s);
which = _index;
}
catch(...) {
// logging here?
}
}

int _index;
};

template<>
struct try_impl<none_type>
{
try_impl(int index)
: _index(index)
{
}
void apply(int& which, none_type& c, const std::string& s) const
{
}

int _index;
};

// attempt to parse all given objects. Return the index of the first one that
// passed
// return -1 if non parse correctly
//
template<class C1, class C2 = none_type, class C3 = none_type, class C4 = none_type, class C5 = none_type>
struct parse_attempt_impl
{
static int apply(const std::string& s,C1 c1, C2 c2 = C2(), C3 c3 = C3(), C4 c4 = C4(), C5 c5 = C5())
{
int which = -1;
try_impl<C1>(0).apply(which, c1, s);
try_impl<C2>(1).apply(which, c2, s);
try_impl<C3>(2).apply(which, c3, s);
try_impl<C4>(3).apply(which, c4, s);
try_impl<C5>(4).apply(which, c5, s);
return which;
}
};

// you will need to make as many of these as you need
template<class C1, class C2, class C3>
int parse_attempt(const std::string& s, C1 c1, C2 c2, C3 c3)
{
return parse_attempt_impl<C1, C2, C3>::apply(s, c1, c2, c3);
}

template<class C1, class C2, class C3, class C4>
int parse_attempt(const std::string& s, C1 c1, C2 c2, C3 c3, C4 c4)
{
return parse_attempt_impl<C1, C2, C3, C4>::apply(s, c1, c2, c3, c4);
}



int main(int argc, char**argv)
{
std::string x(argv[1]);
int which = parse_attempt(x, Class1(), Class2(), Class3());
}

关于c++ - 非确定性操作的设计模式(nondet.factory?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37814866/

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