Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a template have to be declared before every function that uses one?

Tags:

c++

templates

Why is the following code valid

template<class T>
T AddThree(T input)
{
    return input + 3;
}

template<class T>    // If I remove this line it won't compile
T SubtractThree(T input)
{
    return input - 3;
}

But if I comment out the line indicated it won't compile? How come the compiler doesn't still know about template<class T> from the first time it is declared (like anything else declared in the body of the file)?

like image 777
Kvothe Avatar asked Feb 23 '26 23:02

Kvothe


2 Answers

You can think of it as part of the function signature. Maybe it's easier to see the connection if you write the full declaration on one line:

template<class T> T AddThree(T input)
{
    return input + 3;
}

It is like how you need to declare the parameters for each function. You would not expect this to work:

std::string AddThree(std::string input)
{
    return input + "3";
}

std::string SomethingElse(input)
{
    // ...
}

Here, like with the template parameters, you need to declare input in the second function as well as the first. It is the scoping rules of the language :)

like image 173
Magnus Hoff Avatar answered Feb 26 '26 14:02

Magnus Hoff


How would the compiler know that SubtractThree is a templated function? Clearly you don't want a single template declaration to mean everything afterword is a template. You could also imagine designing the C++ spec such that every unrecognized class (T in this case) is seen as a template, but then you risk making template functions when you misspell classes.

like image 42
Shep Avatar answered Feb 26 '26 14:02

Shep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!