如何为函数模板(字符串的冒泡排序数组)编写显式专用化代码

how to code an explicit specialization for a function template (bubble sorting array of strings )

本文关键字:专用 代码 数组 函数模板 字符串 冒泡排序      更新时间:2023-10-16

首先,我对c++还很陌生。我必须编写一个具有显式专门化的函数模板来对整数数组和字符串数组进行排序。

我的主程序

#include <iostream>
#include "sort.h"
int main() {
    int a[] = { 1234, 546, 786, 2341 };
    char* c[6] = { "Harry", "Jane", "Anne", "John" };
    sort(a, 4);
    sort(c, 4);
    for (int i = 0; i < 4; i++)
        std::cout << a[i] << std::endl;
    std::cout << std::endl;
    for (int i = 0; i < 4; i++)
        std::cout << c[i] << std::endl;
    std::cout << std::endl;
}

sort.h文件(包含模板的文件)

template<typename T, typename T1>
void sort(T* items,  T1 count) {
    T1 t;
    for (int a = 1; a<count; a++)
    for (int b = count - 1; b >= a; b--)
    if (items[b - 1] > items[b]) {
        t = items[b - 1];
        items[b - 1] = items[b];
        items[b] = t;
    }
}

问题就在这里:它说:"错误C2912:显式专门化'void sort(char*,int)'不是函数模板的专门化"我对"char*c[]"以及如何对此类型进行专门化感到困惑。

 template<>
    void sort<char ** >(char** p, int count)    
    { 


    }

您必须与主模板签名完全匹配,例如:

template <>
void sort<char *, int>(char ** p, int count)
{
    // ...
}

因此CCD_ 1和CCD_。