'C++ How should functions and templates be declared together
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
Solution 1:[1]
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...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
