c++ - 如何为字符数组制作模板函数特化?

标签 c++ templates function-templates

我正在尝试为字符数组的冒泡排序制作模板函数特化。但出于某种原因,当我要定义函数时,函数名称上有一条错误下划线,我不知道为什么。

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); 

关于c++ - 如何为字符数组制作模板函数特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22826604/

相关文章:

c++ - std::deque 实际上在开始时有恒定时间插入吗?

c++ - 在 MacOSX 上编译 OpenGL 程序时出错 ('ld: library not found for -lopengl32' )

c++ - 模板常量类型转换运算符在 linux (gcc) 下不起作用

css - FontAwesome -> 图标损坏

c++ - 禁止带有迭代器参数的函数模板实例化

c++ - 模板参数作为函数未命名参数

c++ - 在构造函数中使用 "this"启动线程安全吗?

C++在末尾计算跳跃范围

c++ - 模板化函数指针?

node.js - Node : function template without return value