dhh1128 / intent

the intent formal language
https://intentlang.org
2 stars 1 forks source link

eliminate needless duplication in templates #60

Open dhh1128 opened 10 years ago

dhh1128 commented 10 years ago
  1. Consider the following two templates. They differ only in constness. It would be nice to define one in terms of the other, but doing so would require a const_cast or a way to convert end/begin to cend/cbegin:
template <typename K, typename V, typename I>
inline trie<K, V, I>::node_t * trie<K, V, I>::find(K const * key, size_t len) {
    if (len == calc_len) {
        len = keylen(key);
    }
    auto i = std::lower_bound(children.begin(), children.end(), trie_node_child_is_less(*this));
    return (i != children.end() && (*i)->key == key) ? *i : nullptr;
}

template <typename K, typename V, typename I>
inline trie<K, V, I>::node_t const * trie<K, V, I>::find(K key, size_t len) const {
    if (len == calc_len) {
        len = keylen(key);
    }
    auto i = std::lower_bound(children.cbegin(), children.cend(), trie_node_child_is_less(*this));
    return (i != children.cend() && (*i)->key == key) ? *i : nullptr;
}

One way to eliminate this duplication would be to define aliases (cbegin-->begin, cend-->end) in the const version and then call the other method. This is a common pattern (func B is just like func A except the method or variable names have changed.) Do we need a "do like in func A, but substitute X-->Y" statement?