Resources‎ > ‎Programming‎ > ‎C++‎ > ‎C++ Tutorial‎ > ‎Lesson 9‎ > ‎

Sample Solutions

Practice 1

namespace {
    template <typename T> 
    bool less(const T &val1, const T &val2) {
        return val1 < val2;
    }

    template <typename T> 
    bool greater(const T &val1, const T &val2) {
        return val1 > val2;
    }

    template <typename T> 
    bool equal(const T &val1, const T &val2) {
        return val1 == val2;
    }

    template <typename T> 
    T average(const T &val1, const T &val2) {
        return (val1 + val2) / 2;
    }

}

Practice 3 - 5

#include <iostream>
#include <string>

using namespace std;

template <typename T>
class Comp {
    T value;
    Comp(){}
public:
    Comp(T v) : value(v) {}
    bool operator<(const Comp &cv) { return value < cv.value;}
    bool operator<=(const Comp &cv) { return value <= cv.value;}
    bool operator>(const Comp &cv) { return value > cv.value;}
    bool operator>=(const Comp &cv) { return value >= cv.value;}
    bool operator==(const Comp &cv) { return value == cv.value;}
    bool operator!=(const Comp &cv) { return value != cv.value;}
    T getValue() {return value;}
};

// explicit specialisation for "string"
template <>
class Comp<string> {
    string value;
    Comp() {}
public:
    Comp(string v) : value(v) {}
    bool operator<(const Comp &cv) { return value.length() < cv.value.length();}
    bool operator<=(const Comp &cv) { return value.length() <= cv.value.length();}
    bool operator>(const Comp &cv) { return value.length() > cv.value.length();}
    bool operator>=(const Comp &cv) { return value.length() >= cv.value.length();}
    bool operator==(const Comp &cv) { return value.length() == cv.value.length();}
    bool operator!=(const Comp &cv) { return value.length() != cv.value.length();}
    string getValue() {return value;}
};

int main() {
    // example for int type.
    Comp<int> values[] = {32, 44, 559, 321, 98};
    int size = sizeof values / sizeof(int);
    cout << "using as int" << endl;
    for (int i = 0; i < size - 1; i ++) {
        cout << values[i].getValue() << " < " 
             << values[i + 1].getValue() << " : "
             << (values[i] < values[i+1]) << endl;
    }
}

Practice 7

you can check there is only one generated class exists in the memory by checking, say, function pointers of the generated class.

Comments