445,898 Members | 2,039 Online Need help? Post your question and get tips & solutions from a community of 445,898 IT Pros & Developers. It's quick & easy.

# problem on function template

 P: n/a Dear All, Assume I have two templates as follows: //! Add #1: p3 = p1 + p2. template void Add(const _T1 *p1, const _T2 *p2, _T3 *p3, size_t n) { for (size_t i = 0; i < n; ++i) p3[i] = p1[i] + p2; } //! Add #2: p3 = p1 + d2. template void Add(const _T1 *p1, const _T2 d2, _T3 *p3, size_t n) { for (size_t i = 0; i < n; ++i) p3[i] = p1[i] + d2; } Where p1, p2, p3 are pointers pointing to a group of data, and d2 is just a single data. I test the following case: //! A test. int *p1 = new int ; p1 = 1; p1 = 2; p1 = 3; int *p2 = new int ; p2 = 1; p2 = 2; p2 = 3; int *p3 = new int ; Add(p1, p2, p3, 3); And I find that the "Add(p1, p2, p3, 3)" tries to call the second template and givea a compilor error like can not convert int* to int. In fact the first template can also allow the calling and it will give the right results. I can change the seconde template name to "Add2" to get it right. Is there any better way to accomplish it. Thanks, Shuisheng Sep 28 '06 #1
5 Replies

 P: n/a shuisheng wrote: Dear All, Assume I have two templates as follows: //! Add #1: p3 = p1 + p2. template void Add(const _T1 *p1, const _T2 *p2, _T3 *p3, size_t n) { for (size_t i = 0; i < n; ++i) p3[i] = p1[i] + p2; } //! Add #2: p3 = p1 + d2. template void Add(const _T1 *p1, const _T2 d2, _T3 *p3, size_t n) { for (size_t i = 0; i < n; ++i) p3[i] = p1[i] + d2; } Where p1, p2, p3 are pointers pointing to a group of data, and d2 is just a single data. I test the following case: //! A test. int *p1 = new int ; p1 = 1; p1 = 2; p1 = 3; int *p2 = new int ; p2 = 1; p2 = 2; p2 = 3; int *p3 = new int ; Add(p1, p2, p3, 3); And I find that the "Add(p1, p2, p3, 3)" tries to call the second template and givea a compilor error like can not convert int* to int. In fact the first template can also allow the calling and it will give the right results. I can change the seconde template name to "Add2" to get it right. Is there any better way to accomplish it. Thanks, That's because the second function is more specialized than the first function and the partial ordering rules come into the picture. Basically in the first one T2 is deduced to be an int and in the second case T2 is deduced to be an int*... and if you use substitution rules governed by the partial ordering mechanism, the second one is more specialized. > Shuisheng Sep 28 '06 #3

 P: n/a Victor Bazarov åéï¼ Why are your 'Tx' types all different? Do they have to be? Couldn't you simply have a single template argument: template 