Home >Backend Development >C++ >Why Does Template Argument Deduction Fail in Nondeduced Contexts?
Template Argument Deduction and Nondeduced Contexts
In C , template argument deduction allows the compiler to determine the types of template parameters based on the types of arguments passed to the template function or class. However, this mechanism may fail in certain scenarios involving nondeduced contexts.
Consider the following code snippet:
template <class T> struct S { typedef T& type; }; template <class A> A temp(S<A>::type a1) { return a1; } template <class A, class B> B temp2(S<A>::type a1, B a2) { return a1 + a2; }
Here, the S struct serves as a way to obtain a reference to the type held by the template parameter A. However, when attempting to call these functions with integer values, as shown below, the compiler reports errors:
int main() { char c = 6; int d = 7; int res = temp(c); int res2 = temp2(d, 7); }
Error Messages:
Explanation:
The issue arises because the type of A is used solely in a nondeduced context, which means the compiler cannot infer it from the arguments passed to the functions. In particular, S::type is considered nondeduced because it appears within a nested template type and is not directly related to the arguments of temp or temp2.
Solution:
To resolve this issue and enable template argument deduction, the type of A must be explicitly specified when calling the functions, as shown below:
temp<char>(c);
This explicit specification allows the compiler to determine the type of A and successfully instantiate the template functions.
The above is the detailed content of Why Does Template Argument Deduction Fail in Nondeduced Contexts?. For more information, please follow other related articles on the PHP Chinese website!