1

我试图理解下面的示例代码。我知道我们可以明确指定数据类型,但不确定“int, double”和“int, int”是什么意思。以及为什么我们用这种方式编写函数模板而不是 T Tripleit (T Val) { T temp = val * 3; }? 提前致谢。

#include <iostream>

using namespace std;
// why do we write this way instead of T tripleit (T Val) { T temp = val * 3; }?
template <class T, class U>
T tripleit (U val)
{
    T temp = val * 3;

}


int main()
{
    int a=5;
    double d=3.3;

    cout << "Explicit int; int argument: " << tripleit<int>(a) << endl;
    cout << "Explicit int; double argument: " << tripleit<int>(d) << endl;

    // what does <int, double> and <int, int> mean?
    cout << "Explicit int, double; double argument: " << tripleit<int, double>(d) << endl;
    cout << "Explicit int, int; double argument: " << tripleit<int, int>(d) << endl;

    return 0;
}

顺便说一句,输出是:

显式整数;整数参数:15

显式整数;双参数:9

显式 int,双精度;双参数:9

显式整数,整数;双参数:9

4

1 回答 1

2

If the template parameters had more descriptive names, they could look like this:

template <class ReturnType, class ParameterType>
ReturnType tripleit (ParameterType val)
{
  ReturnType temp = val * 3;
  return temp;  // I assume this line is actually present in your code, it makes no sense otherwise
}

With these names, it should be a bit more clear. The function can be used to multiply a number by 3 and convert it to a desired type at the same time.

Invoking the template with both template arguments specified simply suppresses template argument deduction. I think the really interesting case is missing there:

cout << "Explicit double, int; double argument: " << tripleit<double, int>(d) << '\n';

This will pass in a double value 3.3. However, as ParameterType is explicitly specified to be int, the value will be converted to int (perhaps with a warning). Inside the function, temp will be of type double (the first template argument), but the return value will still be 9, so the expected output is 9 or perhaps 9.0 or 9.0e0 depending on the current cout settings for floating-point numbers.

于 2013-11-30T14:57:03.510 回答