C ++ template id not matching template?

I am writing simple code with a template and specialization:

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

I think the char * specialization is correct, but the g ++ report:

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

please help me find a mistake.

+4
source share
2 answers

A function template may be fully specialized and may not be partially specialized; this is a fact.
However, most of the overload time works fine, and you don't need specialization at all:

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

Functions without a template (I mean) prefer function templates, so you can easily get what you pay in your code with an old simple function.

+3
source

. , .

. , , , .

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

+1

Source: https://habr.com/ru/post/1667320/


All Articles