Re: Improving ugly(?) design: Data validation
Seungbeom Kim ha scritto:
Rune Allnor wrote:
On 18 Jun, 04:57, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
wrote:
At the call site, the code might be simply:
if (std::auto_ptr<validation_failure> failure = val(str))
This doesn't work, presumably because the test
checks the address where the the std::auto_ptr
object resides and not the state of the actual
pointer.
The primary reason that the above statement doesn't work is simply
that std::auto_ptr doesn't provide implicit conversion to bool.
You need an explicit call to get(), which makes the initialize-and-test
inside the conditional impossible.
Ops. Sorry. I initially wrote the code with boost::shared_ptr and I
forgot that std::auto_ptr lacks the convertibility to bool. My fault.
Is there a way to overload operators or anything like
that, so I can squeeze both the declaration and the
state test of the std::auto_ptr into the argument of
the if(...) test?
Not that I can think of. However, you can use boost::optional here,
which I think fits the semantics better, and you can write:
if (boost::optional<validation_failure> failure = val(str))
boost::optional doesn't fit well in this scheme, because it has a value
semantic that doesn't work with polymorphic types. You can't even type a
boost::optional<validation_failure> because validation_failure is an
abstract type (according to my definition). Making validation_failure a
concrete type wouldn't help, because you will incur in slicing. Of
course, if you change the design to have validation_failure
non-polymorphic and copy-constructible, that is a viable option.
In addition, std::unique_ptr coming in C++0x, meant to replace std::
auto_ptr, does provide implicit conversion to bool and you can write:
if (std::unique_ptr<validation_failure> failure = val(str))
That would be the best option, for sure.
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]