如何使模板函数专用化字符数组

How to make a template function specialization for a character array?

本文关键字:字符 数组 专用 函数 何使模      更新时间:2023-10-16

我正在尝试为气泡类型的字符数组制作模板函数专用化。但是出于某种原因,当我要定义函数时,我在函数名称上收到一个错误的下划线,我不知道为什么。

template<typename T>
T sort(T* a, T n) {
    int i, j;
    int temp;
    for (i = n - 1; i > 0; i--) {
        for (j = 0; j < i; j++) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}
template<>
const char* sort<const char*>(const char* a, const char* n) {
}

问题:

T替换为 const char * 时,函数签名如下所示:

const char* sort<const char*>(const char** a, const char* n)
                             //        ^^^ T* a -> const char ** a

推荐:

为什么你的签名template<typename T> T sort(T* a, T n)?你没有归还任何东西,你把n当作size_t.我建议将您的签名更改为以下内容:

template<typename T> void sort(T* a, size_t n);

以及您的专长:

template<> void sort<char>(char* a, size_t n);