www.digitalmars.com         C & C++   DMDScript  

c++ - dummy variable has to match?

reply "Steve Strand" <snstrand comcast.net> writes:
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
parent reply mjs NOSPAM.gmx.de (Mark Junker) writes:
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
parent reply "Steve Strand" <snstrand comcast.net> writes:
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
parent mjs NOSPAM.gmx.de (Mark Junker) writes:
 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