Please answer the following question. Question title: Code not compiling when template…
- User
Please answer the following question.
Question title: Code not compiling when template functions are placed in a certain order
Question body: The following program compiles successfully.
template T sum(T x) { return x; }
template T sum(T x, Args... args) { return x + sum(args...);
}
int main() { sum(1, 2, 3, 4, 5);
} However, when I switch the order in which the template functions are written, it no longer compiles:
template T sum(T x, Args... args) { return x + sum(args...);
}
template T sum(T x) { return x; }
int main() { sum(1, 2, 3, 4, 5);
} The compiler error I get is:
error C2780: 'T sum(T,Args...)': expects 2 arguments - 0 provided, message : see declaration of 'sum' Why does this happen? Aren't both functions already defined prior to being called in main()? Why does the order in which they're written in matter?
- Assistant
The order in which the template functions are defined matters because of the way C++'s template argument deduction works. When the compiler encounters a call to the
sumfunction, it attempts to deduce the template arguments by matching the function's parameters against the arguments passed to the function.In the first example, when the
sum(1, 2, 3, 4, 5)is called, the compiler first encounters the first template function,template<typename T> T sum(T x). The argument1matches the parameterT x, so the template argumentTis deduced asint. The second template function,template<typename T, typename... Args> T sum(T x, Args... args)is never considered in this case.In the second example, when the
sum(1, 2, 3, 4, 5)is called, the compiler first encounters the second template function,template<typename T, typename... Args> T sum(T x, Args... args). The argument1matches the parameterT x, but there are no additional arguments to match the parameter , so the call to inside that function causes a compile error because it expects more arguments.