Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template-id does not match any template?

Tags:

c++

templates

I write a simple code with 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 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 the bug.

like image 548
linrongbin Avatar asked Jan 20 '17 05:01

linrongbin


2 Answers

Function template can be fully specialized and cannot be partially specialized, this is a fact.
That said, the most of the time overloading works just fine and you don't need any 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;
}

Non template functions are (let me say) preferred over function templates, thus you can easily got what you pay for in your code with an old plain function.

like image 52
skypjack Avatar answered Oct 15 '22 13:10

skypjack


You can't use the template specialization for function overloading. if this is what you want to do.

Template specialization is meant for specializing the objects and not bare functions. Probably you can change you code something like this to do what you want to do.

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

As you can see from the code above, you use specialization for ABC and using the same in the function HelloFunction

like image 21
Deepak Kr Gupta Avatar answered Oct 15 '22 12:10

Deepak Kr Gupta