2010年9月15日 星期三

[C++ template]有趣的template, 常被誤解的型別

通常我們要做==比較時, 會希望兩邊的型別是相同的, 如果是base type如int, double, char, 這些會自動轉型, 但是遇到class或是template時怎麼辦, 其實可以在一個class裡實作出一個template的operation overload就ok了..範例如下...

下面的例子可能比較複雜一點,  但其實也只是在一個template class裡再做另一個template member function而已...

template<typename T>

class MyType {

public:

    MyType(T value) {

        m_value = value;

    };

    T GetValue() {

        return m_value;

    };

    template<typename T2> bool operator==(T2 AnotherType) {

        if(this->GetValue() == AnotherType.GetValue()) {

            return true;

        }

        return false;

    };

public:

    T m_value;};

int main() {

    MyType<int> myInt(5);

    MyType<double> myDouble(5.0);

    if(myInt == myDouble) {

        cout << "Yes!!" << endl;

    }

    return 0;

}

-----

所謂的template型別(這裡指的是被指定後的型別), 應該這麼考慮的..

"MyType<int>"是一種型別..

"MyType<double>"亦是另一種型別

 

試想在所有的程式裡..宣告一個變數一定是 "型別名" "變數名"

所以上面兩種是不同型別, 另外在偏特化的例子中, 

SomeType<int, 6>

SomeType<int, 5>

這兩個是不同型別, 寫個程式來表達一下好了..

 

-----美麗的分隔線------

template <typename T>

inline T cost& max(T const& a, T const& b) {

    return a < b ? b : a;

}

 

int main() {

    std::string s = "apple";

    ::max("123456", "567890");    // OK!

    ::max("12345", "123456");      // ERROR!!

    ::max("apple", s);                   // ERROR!!

    return 0;

}

為什麼不行呢, 因為型別不同, 很多人可能會誤以為不都是字串嗎, 特別是第二個...

真是不好意思啊, 在compiler的眼裡,

"12345"和"123456"的型別, 分別是char[5]及char[6]

所以理所當然, 第三個max也不行了..一個是char[5], 一個是string...

要小心啊..型別的問題....

沒有留言: