같은 방법 및 제한 나중에 편리하게 표현할 수 있도록 앞쪽에 자리 잡은 뒤 :
#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());
}
나는 당신이 무엇을 요구하고 있는지 명확하지 않습니다. 보다 간결한 예제를 줄 수 있습니까? 당신은 단지 당신이 programm에있는 어떤 타입으로 메시지를 deserialize하려고 시도함으로써 실제 직렬화 된 타입을 찾으려고 하는가? 그것은 매우 나쁜 디자인입니다. 그것이 다른 것이라면 명확히하십시오. – SergeyA
정상적인 제어 흐름에 대한 예외 처리를 남용하고 있습니다. 대신에'ClassX'에 상태를주고 'bool'으로 변환하여 성공을 확인하면 쉽게 해결할 수 있습니다. – nwp
@ SergeyA, 네가 옳은 것 같아. 입력은 XML DOM이며 클래스 계층 구조에 맞게 파싱하거나 예외를 throw하려고합니다. 이 특정 측면은 구문 분석이 모호 할 수 있으며 많은 가능한 클래스로 XML 요소를 구문 분석해야합니다. – fferri