c++ - dummy variable has to match?
- Steve Strand (23/23) Sep 05 2003 The program below compiles fine, as long as the definition of fun2 uses ...
- mjs NOSPAM.gmx.de (Mark Junker) (10/14) Sep 07 2003 will become to:
- Steve Strand (3/3) Sep 07 2003 Experiment shows that passing the argument to fun2 by value or
- mjs NOSPAM.gmx.de (Mark Junker) (5/8) Sep 07 2003 Now I understand.
The program below compiles fine, as long as the definition of fun2 uses the same "template dummy variable" used in the declaration. Member function fun1 has no such restriction. Why is this? I ask because sometimes inquiring into mysteries pays off with unexpected valuable knowledge. #include <iostream.h> template <int kk> //dummy variable is kk class test { int val; public: test() {val=0;}; int fun1(); template <int rr> //dummy variable is rr friend int fun2(test<rr> a); }; template <int ss> //dummy variable is ss int test<ss>::fun1() {return val+ss;}; template <int rr> //dummy variable has to be rr?! int fun2(test<rr> a) {return a.val+rr;}; int main() { test<5> a; cout << a.fun1() << '\n'; //test member function cout << fun2(a) << '\n'; //test friend function }
Sep 05 2003
Try using a reference instead.template <int rr> //dummy variable is rr friend int fun2(test<rr> a);will become to: template<int rr> friend int fun2(test<rr> &a);template <int rr> //dummy variable has to be rr?! int fun2(test<rr> a) {return a.val+rr;};And this will become to template<int rr> int fun2(test<rr> &a) { return a.val+rr; } Should compile without warning when you don't use const objects. Regards, Mark Junker
Sep 07 2003
Experiment shows that passing the argument to fun2 by value or reference makes no difference - the "template dummy variable" still has to match.
Sep 07 2003
Experiment shows that passing the argument to fun2 by value or reference makes no difference - the "template dummy variable" still has to match.Now I understand. Yes, it seems that you're right. It should only take care of the type not of the name. Regards, Mark Junker
Sep 07 2003