1

so i read the following on this page: http://warp.povusers.org/programming/template_declarations.html

template<typename T> T min(T v1, T v2);

Many C++ programmers are surprised that the above even compiles rather than giving an error message outright. (It will give a linker error if the function has not been defined and instantiated somewhere, but the declaration above is completely valid.)

Basically what the code above does is that when it's called, the compiler will create a declaration of the min() function with the specified template parameter type. It's then up to the linker to try to find a definition of this specific function somewhere (which obviously must be provided by the programmer somehow, or else a linker error will be issued, naturally)

So this leads to my question:

if i have in file1.cpp the following:

template <typename T>
void foo(T);

int main()
{
foo<int>(1);
return 0;
}

And then in file2.cpp the following:

void foo(int)
{ //... }

So i thought that file1.cpp and file2.cpp would work. By reading the quote above, i thought, that this code will work, because if i would call in file1.cpp in main the function "foo", the compiler will generate me a function declaration exactly similar to this:

void foo(int);

but apparently, it is not.

But why is it not working? Isn't the compiler generating this function declaration, so that the linker can link the function in file1.cpp with the one in file2.cpp? Or does the compiler generate "different" function declarations, when using templates, if you know what i mean? Sorry, i am really confused.

Did I misunderstood something? Would appreciate help.

Sorry for my english.

Avva
  • 150
  • 6
  • 1
    It is a different function declaration. The `int` specialization of `foo` is similar to, but not actually the same as from the compiler's perspective, a non-template function `foo` that takes an `int` argument. [This question](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) is about classes but the same basic mechanism applies for functions. – Nathan Pierson Sep 16 '21 at 00:29
  • 1
    This is why proper terminology is important, so to fix the quote *"... if the function ** – StoryTeller - Unslander Monica Sep 16 '21 at 00:47

0 Answers0