#include <iostream>
#include <cstring>
template <class T>
T maxn(T range[], int size);
// create a specialization for an array of pointer-to-chars.
template <>
char* maxn<char* []>(char* range[], int size);
It keeps giving me an error that says: no instance of function template "maxn" matches the specified type.
I've checked the syntax for template specialization over and over, and it looks fine to me (unless I'm missing something) and can't figure out why this won't work. The error makes it sound like the compiler is searching for a template for char* instead of using the specialized one. Or something along those lines. Any help would be greatly appreciated.
You can't declare templates or specializations - you just have to straight out define them.
I successfully declared a template specialisation. Didn't try the other - so don't know about that. (Even if you can declare it, I don't see that there's much point as you have to put the definition in the header too ;) )
@OP A definition of a function includes it's body:
1 2 3 4
int foo(double, const std::string&)
{
return 1;
}
A declaration just provides the return type, name and parameter list: int foo(double, const std::string&);
@Xander314, I'm not sure I follow you guys. You can put a template declaration in the header and define it further in the program just like a normal function. Like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
template <typename T>
void ShowArray(T * arr[], int n);
int main()
{
// ....
}
template <typename T>
void ShowArray(T * arr[], int n)
{
usingnamespace std;
cout << "template B\n";
for (int i = 0; i < n; i++)
cout << *arr[i] << ' ';
cout << endl;
}
You don't have to define the body of a template right away, you can use a prototype just like normal functions.
Huh, I get compiler errors about multiply defined functions and undefined stuff when I try to compile anything with both templated function declarations and definitions.
Huh, I get compiler errors about multiply defined functions and undefined stuff when I try to compile anything with both templated function declarations and definitions.
Because when you declare and implement the function at the same time, you are implicitly telling the compiler to inline the function. When you implement it separate from the declaration, you're aren't. In that case, the compiler is actually generating a function call, meaning the function will get compiled, with the same mangled name, in multiple translation units (ie, cpp files).
To fix the problem, the keyword "inline" should be used.