If templates worked how I would like them to work, I'd be able to do the following:
It appears that templates do not in fact work like how I would like them to work, and GCC (4.1.2) comes up with a laundry-list of complaints:
The only one that vaugely seems sensible is the "private" one, but only because it can't seem to figure out the friend line.
After trying dozens of ways of coding this concept, the closest I've got to getting it to work is the following:
which "only" has a link error (do_foo doesn't get instantiated, so possibly this suppresses the other errors). Shuffling things around and/or adding prototypes to above the class definition doesn't help with this.
Is there any way to get this to work, or should I just keep with the stop-gap solution of making X public?
Code:
template <int N>
class A
{
private:
int X[N];
public:
template <int M>
void foo(const A<M> &Src) { X[N - 1] = Src.X[M - 1]; }
template <int M>
friend void A<M>::foo(const A<N> &Src);
};
int main(void)
{
A<3> A3;
A<4> A4;
A3.foo(A4);
}
Code:
templtest.cpp: In instantiation of "A<3>": templtest.cpp:16: instantiated from here templtest.cpp:11: error: prototype for "void A<N>::foo(const A<3>&)" does not match any in class "A<N>" templtest.cpp:8: error: candidate is: template<int N> template<int M> void A::foo(const A<M>&) templtest.cpp: In instantiation of "A<4>": templtest.cpp:17: instantiated from here templtest.cpp:11: error: prototype for "void A<N>::foo(const A<4>&)" does not match any in class "A<N>" templtest.cpp:11: error: candidates are: void A<N>::foo(const A<3>&) templtest.cpp:8: error: template<int N> template<int M> void A::foo(const A<M>&) templtest.cpp: In member function "void A<N>::foo(const A<M>&) [with int M = 4, int N = 3]": templtest.cpp:18: instantiated from here templtest.cpp:5: error: "int A<4>::X [4]" is private templtest.cpp:8: error: within this context
After trying dozens of ways of coding this concept, the closest I've got to getting it to work is the following:
Code:
template <int N> class A;
template <int N, int M> void do_foo(const A<M> &Src, A<N> &Dest);
template <int N>
class A
{
private:
int X[N];
public:
template <int M>
void foo(const A<M> &Src) { do_foo(Src, *this); }
template <int M>
friend void do_foo(const A<M> &Src, A<N> &Dest);
};
template <int N, int M> void do_foo(const A<M> &Src, A<N> &Dest)
{
Dest.X[N - 1] = Src.X[M - 1];
}
int main(void)
{
A<3> A3;
A<4> A4;
A3.foo(A4);
}
Is there any way to get this to work, or should I just keep with the stop-gap solution of making X public?
Comment