otl_stream manipulation (set_if_not_null)

To read from any input_stream like OTL (otl_stream), you need to first read a value, and then test. Sometimes like in case of otl_stream test if the value was really NULL. The database could have had null value in the field, however, since otl_stream needs to set some value in your variable, it would set the default, it deems fit. for eg:

otls >> some_float;

The some_float is actually a float, so how would otl_stream set null in it? Instead it sets 0.0F.

After having read the field, you need to check with the otl_stream object, if the read value was actually a null:

otls.is_null()

If you wanted to have a different value as default, then you need to write it this way:

float tmp;
otls >> tmp;
if(!otls.is_null())
    some_float = tmp;

There are 2 issues with this approach:

1. you cannot do something like this:
otls >> some_bool >> some_float >> some_std_string;

2. Consider if you had many more objects for which you need to first check if the database had null for it, there would be too many such checks and tmp variables of different kind.

So how about using template class for doing this to avoid writting code for different types of objects which essentially does the same thing for every type?

With template classes the ugliness of the code increases, because you need to specify the template parameter for any object and you could end up with a lot of intimidating angular brackets “< >”:

otls >> SomeClass<bool>(some_bool) >> SomeClass<float>(some_float) >> SomeClass<std::string>(some_std_string) >> var1 >> var2;

This problem can be handled through a template function.

Consider:
otls >> set_if_not_null(some_float);

Here’s the code for it:

template <class T>
struct SINN //Set If Not Null
{
    T& dest_;
    SINN(T& dest) : dest_(dest) {}
};
template <class T>
otl_stream& operator >> (otl_stream& otls, SINN<T>& sinn)
{
    T temp;
    otls >> temp;
    if(!otls.is_null())
        sinn.dest_ = temp;
    return otls;
}
template <class T>
SINN<T> set_if_not_null(T& dest)
{
    return SINN<T>(dest);
}

This solution address both the issues discussed above and you could peacefully write code like this:

otls >> set_if_not_null(some_bool) >> set_if_not_null(some_float)
     >> set_if_not_null(some_std_string) >> var1 >> var2;

Advertisements

1 Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s