繁体   English   中英

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

[英]C++ template-id does not match any template?

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

#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;
}

我认为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

请帮我找到这个bug。

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

#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;
}

非模板函数(比方说) 优先于函数模板,因此您可以使用旧的普通函数轻松获得您在代码中支付的费用。

您不能使用模板特化来进行函数重载。 如果这是你想要做的。

模板专门化用于专门化对象而不是裸功能。 也许你可以改变你这样的代码来做你想做的事。

template<typename T>
struct ABC {
    T type;
    ABC(T inType) : type(inType) {}
};

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

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

int main()
{
    HelloFunction(ABC<int>(1));
    HelloFunction(ABC<const char*>("char"));

    return 0;
}

从上面的代码中可以看出,您对ABC使用了特殊化,并在函数HelloFunction使用了HelloFunction

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM