Boost logo

Boost Users :

Subject: [Boost-users] Refactoring template functions. Needing help with compile time if statements.
From: Ryan McConnehey (mccorywork_at_[hidden])
Date: 2009-06-05 02:18:42


I'm trying to refactor my code to remove some code duplication.
Currently I have a template that takes a pointer to store information, a
map with the information and a text string. I've specialized the
function to account for some fundamental types. As these cases have
increased I notice the only difference between the function is how I'm
accessing the iterator for the map.

template<>
void Customize::addVariableType(TiXmlElement *const xml,
std::map<string, bool> const& map, string const& mapType) const {
    std::map<string, bool>::const_iterator itor;
    for (itor = map.begin(); itor != map.end(); ++itor) {
        itor->second;
    }
}

template<typename T>
void Customize::addVariableType(TiXmlElement *const xml,
std::map<string, T> const& map, string const& mapType) const {
    std::map<string, T>::const_iterator itor;
    for (itor = map.begin(); itor != map.end(); ++itor) {
        itor->second.base_type_value();
    }
}

I'm using stlSoft's true_typedef for some custom types.

STLSOFT_GEN_OPAQUE(fundamental_type);
typedef stlsoft::true_typedef<unsigned short, fundamental_type>
uint16_type;

Most of the maps are comprised of these custom types. That's why the
generic template accesses the underlying value of the iterator's second
value. Also this accounts for the specialization for fundamental
types. Since both the template and the specialization template have the
same functionality but access the second map value differently I'm
trying to refactor to have another function retrieve iterator value.
Below is what I've tried so far.

template<>
bool accessValue(bool const& value) const {
    return value;
}

//V is the underlining type of W. If W was uint16_type then V should be
unsigned short.
template<typename V, typename W>
typename V accessValue(typename W const& value) const {
    return value.base_type_value();
}

I understand that I've moved the difficulty out of addVariableType into
accessValue. Unfortunately, accessValue gives an error that typename V
cannot be deduced. Also for each fundamental type I have to add an
overload to accessValue. This turns into the same problem I'm facing
with addVariableType but with less code to copy. Is there a way to have
a template function that has an if statement to choice how to access the
value? I've tried to use BOOST_TYPEOF_TPL and boost::is_class but was
unsuccessful in making it work.

Any help would be really helpful.

Ryan


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net