Question about C ++ template

Suppose the following template definition (code does not make sense):

template<class X, class Y>
bool FooBar(const Y& val) { return sizeof(X) + 4; }

I found that the following call code is legal:

float temp = 0.f;
FooBar<int>(temp);

As you can see, the parameter of the second type Ycan be omitted. The compiler infers the type Yby looking at the type of the argument temp.

Does this rule or C ++ template spec allow this? I was very surprised to see this.

+3
source share
4 answers

This is the output of the template argument; this is the same as if you used Xvalues ​​as a parameter type FooBarand called it without any template arguments. The IBM compiler site document has a document with more details.

+5
source

14.7.1 2:

, , , .

, - , :

14.8.2:

, . , ....

.

: ISO/IEC 14882: 1998 (E)

+3

" ". . , 14.7.1. , .

+1

You do not have to specify each type parameter. Essentially, the compiler computes Y from the type of the passed parameter, and you specified X in your declaration. Another difference between Java and C ++.

+1
source

Source: https://habr.com/ru/post/1789917/


All Articles