c++ template display argument type inference

Template display arguments

In some cases, the compiler cannot infer the actual parameter types of the template. In some other cases, we want the user to control the instantiation of the template. These two situations occur most often when the function type is different from any type in the parameter list.

Specify the displayed template arguments

In some cases, the compiler cannot infer the type of the template argument. In some other cases, we want to allow users to control template instantiation. These two situations occur most often when the return type of the function and any type of the parameter list are different.

Specify the displayed template arguments

As an example that allows the user to specify the type of use, we will define a function template named sum that accepts two different types of parameters. We allow users to specify the type of result. In this way, the user can select the appropriate accuracy.

template <typename T1,typename T2,typename T3>
T1 sum(T2,T3);

In this example, there is no function argument type to determine the type of T1. The caller must provide a display template argument for T1 each time sum is called.

The way we provide display template arguments is different from the way we define class template instances. The display template arguments are given in angle brackets, after the function name and before the parameter list.

auto val3 = sum<long,long>(i,lng);

This call displays the type of the specified T1. The types of T2 and T3 are judged by the compiler from the types of i and long.

The display template argument matches the corresponding template parameters in the order from left to right; the first template actually participates in the first template parameter matching, the second actually participates in the second parameter matching, and so on. Only the display template actual parameters of the tail parameters can be omitted, and only if they can be inferred from the function parameters. If our sum function is written in the following form:

template <typename T1,typename T2,typename T3>  T1 sum(T2 a,T3 b)
{
    return a+b;
}
int main()
{
    auto data = sum<long,long>(1,2);
    auto data2 = sum<long>(1,2);
    return 0;
}

Both of these two writing methods are possible, the compiler can infer the return result by itself

    string D1("a");
    string D2("n");
    auto data2 = sum<string>(D1,D2);

These examples tell us that when we provide some actual template parameters, the compiler has a certain ability to infer.

Guess you like

Origin blog.csdn.net/qq_32783703/article/details/105088705