C++ template-id与任何模板都不匹配?

lin*_*bin 5 c++ templates

我用模板和专业编写了一个简单的代码:

#include <iostream>

template <class T>
int HelloFunction(const T& a)
{
    std::cout << "Hello: " << a << std::endl;
    return 0;
}

template <>
int HelloFunction(const char* & a)
{
    std::cout << "Hello: " << a << std::endl;
    return 0;
}

int main()
{
    HelloFunction(1);
    HelloFunction("char");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我认为char*的专业化是正确的,但是g ++报告:

D:\work\test\HelloCpp\main.cpp:11:5: 
error: template-id 'HelloFunction<>' for 'int HelloFunction(const char*&)' does not match any template declaration
Run Code Online (Sandbox Code Playgroud)

请帮我找到这个bug.

sky*_*ack 4

函数模板可以完全特化,不能部分特化,这是事实。
也就是说,大多数时候重载工作得很好,你根本不需要任何专门化:

#include <iostream>

template <class T>
int HelloFunction(const T &a) {
    std::cout << "Hello: " << a << std::endl;
    return 0;
}

int HelloFunction(const char *a) {
    std::cout << "Hello: " << a << std::endl;
    return 0;
}

int main() {
    HelloFunction(1);
    HelloFunction("char");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

非模板函数(让我说)比函数模板更受欢迎,因此您可以使用旧的普通函数轻松地在代码中获得您所付出的代价。