天天看點

C++ template overload

運作結果:

may be you are right
may be you are right
          
          
Program ended with exit code: 
           

Test.cpp

#include <iostream>

using namespace std;

template <typename T>
void show(T a, size_t);

template <typename T>
void show(T a);

int main() {
    int a[] = {, , , , , , , , ,};
    int b[sizeof(a) / sizeof(int)] = {};  // 建立同數組a相同大小的數組b并将其所有元素初始化為0

    char aa[] = "may be you are right";
    char bb[strlen(aa) + ]; // 多配置設定一個位元組存儲截止符'\0'

    memcpy(bb, aa, strlen(aa) + );
    memcpy(b, a, sizeof(a));  // 因為memcpy是逐位元組拷貝,而數組b為int類型,拷貝的長度應為sizeof(a)

    show(a, sizeof(a) / sizeof(int));
    show(b, sizeof(b) / sizeof(int));
    show(aa);
    show(bb);

    return ;
}

template<typename T>
void show(T a, size_t len) {
    for (int i = ; i < len; i++)
        cout << a[i] << ' ';
    cout << endl;
}

template<typename T>
void show(T a) {
    while ((*a) != '\0')
        cout << *a++;
    cout << endl;
}
           

繼續閱讀