功能专业化不起作用

时间:2015-01-31 22:19:37

标签: c++ templates template-specialization

我在编写函数特化时遇到问题。

template <class type>
void is(type tab, int n) {
    string key;
    int i, j;

    for(i=1; i<n; i++){
        key=tab[i];
        j=i-1;
        while(j>=0 && tab[j]>key){
            tab[j+1]=tab[j];
            j--;
        }
        tab[j+1]=key;
        }
    }

template <>
void is <char **> (char *tab[], int n){
    char* key;
    int i, j;

    for(i=1; i<n; i++){
        key=tab[i];
        j=i-1;
        while(j>=0 && strcmp(tab[j], key)>0){
            tab[j+1]=tab[j];
            j--;
        }
        tab[j+1]=key;
    }
}

如果我是正确的,当我用is<char **>(tab, n)调用函数时,程序应该使用专门化。即便如此,我甚至无法编译它。我得到的只是sort.cpp:(.text+0x0): multiple definition of void is<char**>(char**, int)。我真的很感激所给予的任何帮助。

1 个答案:

答案 0 :(得分:0)

除了事实之外,你的问题与模板专业化没有多大关系 - 因为它是完全专业化的 - 第二个is不再是模板。

虽然可以在多个翻译单元中定义模板,但可能不会多次定义普通函数。

@Barry接近解决方案,但忘记原始模板不必是inline,只需要专业化。

这导致与任何旧函数相同的两个解决方案(请记住:专业化 任何旧函数):

template <> void is <char **> (char *tab[], int n);
// definition in *one* .cpp file

template <>
inline void is <char **> (char *tab[], int n){
    /* ... */
}

然而,function template specialization is tricky and should often be avoided in favor of overloading