code:
#include <stdio.h>
T foo(T x,T y);
int main(void)
{
}
template <typename T>
T func(T x,T y) {return x y;}
error:
3 | T foo(T x,T y);
| ^
main.c:3:7: error: unknown type name ‘T’
3 | T foo(T x,T y);
| ^
main.c:3:11: error: unknown type name ‘T’
3 | T foo(T x,T y);
| ^
main.c:9:10: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token
9 | template <typename T>
| ^
I thought I should declare the template, so I tried to declare the template before declaring the function:
#include <stdio.h>
template <typename T>
T foo(T x,T y);
int main(void)
{
}
T func(T x,T y) {return x y;}
But this is still wrong, so wondering how should I declare the template
CodePudding user response:
foo()
and func()
are not the same function. And in the 1st example, foo()
is not a template, and in the 2nd example, func()
is not a template, so that is why the compiler doesn't know what T
is in them.
Like any other function, if you are going to separate a template function's declaration from its definition (which is doable, though do be aware of this issue), they need to match either other in name and signature, including the template<>
, eg:
template <typename T>
T foo(T x,T y);
int main()
{
// use foo() as needed...
}
template <typename T>
T foo(T x,T y) {return x y;}
Though, if you move foo()
's definition above main()
, you can declare and define it in one operation:
template <typename T>
T foo(T x,T y) {return x y;}
int main()
{
// use foo() as needed...
}
CodePudding user response:
Sorry I didn't notice when I posted this question, I wish I could make a function that takes two floats or integers and returns the value they add, I found the problem when declaring the function, I don't know how to declare it template. Thanks to @Remy Lebeau for answering my question, I should have written the template in both places together.