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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With