-1

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

  • 2
    `foo` and `func` are separate functions and both need to have the template types specified – Alan Birtles Apr 28 '22 at 20:10
  • 2
    If you are separating declaration from definition, both must have `template<...>` specifier. – Yksisarvinen Apr 28 '22 at 20:14
  • 1
    "this is still wrong" as evidenced by what? – n. m. could be an AI Apr 28 '22 at 20:15
  • Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). This will be covered in the chapter(s) on templates. – NathanOliver Apr 28 '22 at 20:21
  • It is not clear to me what you are trying to do. From the text it seems that you want a function and a separate function template. If that is the case, what do you expect `T` to be in the non-template function? Please elaborate on what you are trying to achieve. – user17732522 Apr 28 '22 at 20:29

1 Answers1

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...
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770