简体   繁体   中英

Class Template Specialization vs. Function Overloading

I thought that I wanted to template function specialization, but this stackoverflow article makes me think that I should really by doing function overloading. However, I'm just not seeing how I could achieve what I want.

I have been able to achieve the goal with a class template specialization, but I don't like the fact that I have so much replicated code between the template class and the specialized class.

What I have is a class with, among other things, two keys that are used for sorting the class objects. Moreover, I want to create a method, match() that for string will return true if the starting portion of the string matches (ie "aaa" would match "aaa:zzz" because the first three characters of both strings are 'aaa'), but ints, shorts, etc. would only match if its an exact match (ie 1 == 1).

I got this to work using class specialization, as shown below:

template <class    KEY2_TYPE>
class policy_key_c
{
public:

    policy_key_c (int          _key1,
                  KEY2_TYPE    _key2) :
        key1(_key1),
        key2(_key2)
        {};


    virtual ~policy_key_c(void) {};


    virtual std::string strIdx (void) const {
        // combine key1 and key2 into an index to be returned.
    }


    //
    // operator <
    //
    virtual bool operator< (const policy_key_c    &b) const {
        return (operator<(&b));
    }


    virtual bool operator< (const policy_key_c    *p) const {

        // if the primary key is less then it's less, don't check 2ndary
        if (key1 < p->key1) {
            return (true);
        }


        // if not less then it's >=, check if equal, if it's not equal then it
        // must be greater
        if (!(key1 == p->key1)) {
            return (false);
        }

        // its equal to, so check the secondary key
        return (key2 < p->key2);
    }



    //
    // operator ==
    //
    virtual bool operator== (const policy_key_c    &b) const {
        return(operator==(&b));
    }


    virtual bool operator== (const policy_key_c    *p) const {

        // if the primary key isn't equal, then we're not equal
        if ((key1 != p->key1)) {
            return (false);
        }

        // primary key is equal, so now check the secondary key. 
        return (key2 == p->key2);
    }


    //
    // match
    //
    virtual bool match (const policy_key_c    &b) const {
        return(operator==(&b));
    }


    virtual bool match (const policy_key_c    *p) const {
        return (operator==(p));
    }


protected:

    int          key1;    // The primary key
    KEY2_TYPE    key2;    // The secondary key.
   // ... other class data members ....
};




// Now specialize the template for a string as the secondary key
//
template <>
class policy_key_c<std::string>
{
public:
    //
    // .... all the other functions
    //

    //
    // match
    //
    virtual bool match (const policy_key_c    &b) const {
        return(operator==(&b));
    }


    virtual bool match (const policy_key_c    *p) const {
        // do a prefix string match rather than a complete match.
        return (key2.substr(0, p->key2.lenght()) == p->key2);
    }


protected:

    int            key1;    // The primary key
    std::string    key2;    // The secondary key.
   // ... other class data members ....
};

I don't like this solution because there is so much replicated code. The only thing that behaves differently is the match function. When key2 is an int, short, or char match behaves like == wherease if key2 is a std::string I want it to do a prefix match.

Is there a "more efficient" way of doing this? Could this be done with function overloading of the match function? If it can be overloaded, I would appreciate ideas on how. I've tried several variations of overloading and failed miserably.

Thanks in advance.


Edit 10/12/10

I started to apply PigBen's answer and was able to get it to work with my problem as stated above. Then I tried it on my actual code and realized that I oversimplified my problem. I actually have two template parameters, but I'm attempting specialization based on one.

template <int KEY1_VAL, class KEY2_TYPE> class policy_key_c

This was to allow typdefs such as:

typedef    policy_key_c<1, int>           int_policy;
typedef    policy_key_c<2, std::string>   str_policy;

But I'm finding that function specialization appears to want all of the template parameters to be specified.


Edit 10/12/10

PigBen's suggestion solved the problem as stated.

Later I realized my problem is slightly different, with two template parameters and I was trying to specialize on only one. That really changes the question. And it looks like I need to do something like done here (which is similar to James McNellis's suggested solution).

If the only thing that behaves differently is a single function, then you don't have to specialize the whole class, you can just specialize that function. I'm not sure if there's syntax to do this when the function is defined within the body of the class, but if you define the function externally, then you can do it like this:

template <class T>
class X
{
    void f();
};

template <class T>
void X<T>::f()
{
    // general code
}

template<>
void X<std::string>::f()
{
    // specialized code
}

For multiple template parameters

template<int K, typename T> class X;
template<int K, typename T> void friend_func(X<K,T> &);

template<int K, typename T>
class X
{
public:
    void class_func();
    friend void friend_func<>(X &);
};

template<int K, typename T>
void X<K,T>::class_func()
{
    friend_func(*this);
}

template<int K, typename T>
void friend_func(X<K,T> & x)
{
    // non specialized version
}

template<int K>
void friend_func(X<K,std::string> & x)
{
    // specialized version
}

If the only thing that is different is the match function, then have the class call the match function using a function pointer instead of adding the match function inside of the class (similar to C's qsort function). Write your two match routines as independent functions, and assign each instance of your class a pointer to the appropriate match function. It's admittedly a C-ish approach to the problem but it should work.

You can have a match() function template delegate to a class template member function. Then you can specialize the class template:

// primary template for general-purpose matching
template <typename T>
struct match_impl
{
    static bool match(const T& x) { return true; }
};

// specialization for std::string matching
template <>
struct match_impl<std::string>
{
    static bool match(const std::string& x) { return true; }
};

template <typename T>
bool match(const T& x)
{
    return match_impl<T>::match(x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM