Why do we need the template keyword in C ++?

Feature Pattern:

template<class T> T 
max(T a, T b){return (a > b)? a: b;}

using:

max<int>(a, b); // Yeah, the "<int>" is optional most of the time.

but if you allow, we can write a template as follows:

T max<class T>(T a, T b){return (a > b)? a: b;} 
//I know the return type T is not in its scope, don't focus on that.

Thus, we can maintain the same form of declaration and use it as a regular function does. and you don’t even need to enter and enter the keyword “template”. I think the template template will be the same? So is there any other reason for the pattern to become the form we know today?

i reshaped so you don't focus on the return type:

auto max<class T>(T a, T b) -> T {return (a > b)? a: b;}
//This is C++11 only and ugly i guess. 
//The type deduce happens at compile time 
//means that return type really didn't to be a problem.
+3
source share
4 answers

, :
, - , , , 8 .

:
, template, , , , ++ ( ).

+2

T, ,

<class T> T max(T a, T b){return (a > b)? a: b;} 

, <class T> - , , . template , < , .

, , ++ 11, .

+2

, : , ++, , , ( , ). , , .

So, the reason is that, reading your example, T is the first name, but it has not been declared before, so the compiler has no idea what it is or what kind of expression it is.

+1
source

You quickly solve problems with this approach:

template <typename> int f(); // Current declaration syntax, type template argument.
template <int> int f();      // Current declaration syntax, non-type template argument.

void f<class>(); // New declaration syntax, type argument. 
void f<int>(); // New declaration syntax, non-type argument.
(void) f<int>(); // (void) is a cast , f is instantiation of f<class> with type int.
+1
source

All Articles