簡體   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