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)?
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With