Gianni Mariani said:
Norman Evanson wrote []
Given a templated class
template <class T, int I> foo { /* ....*/ }
how do I go about( if indeed it's possible) adding (for example) a
foo<T,x> to a foo<T,y> where x!=y
[]
you mean somthing like :
template <class T, int I>
struct foo
{
...
foo( stuff_type v );
template <int Iother>
foo & operator add( const foo<T,Iother> & other )
{
return foo( this.suff + other.stuff )
}
...
};
That didn't compile (But its more elegant than the 4 parameter template I
first cooked up
BTW: I see no natural choice for the type of foo<T,x> + foo<T,y>.
Symmetry speaks against either foo<T,x> or foo<T,y> unless x==y.
Where x and y differ, Foo<T, x+y> and simply int seem to make
sense as the return type for addition. Overloading restrictions
mean you can only choose one, of course.
Try this. It compiled on bcc32 v5.5 and g++ 2.95 under cygwin/win2k.
(I no longer trust just one compiler
-Fazl
#include <iostream>
using std::cout;
template <class T, int I> struct Foo {
T m_t; //value set by ctor
int size; //could make static
explicit Foo( T t ) : m_t(t), size(I) {}
//Usual op+
Foo operator+( const Foo& rhs ){
cout <<"In usual Foo<T,"<<I<<">
Foo<T,"<<I<<">:
perator+(Foo<T,"<<I<<">rhs)\n";
Foo<T,I> sum = *this;
//'add' rhs to sum, however you want to
return sum;
}
//Parameterise int argument.. returning Foo<T,size+rhs.size>:
template<int X> Foo<T,X+I> operator+(const Foo<T,X>& rhs){
cout <<"In Foo<T,"<<X+I<<"> Foo<T,"<<I<<">:
p+(Foo<T,"<<X<<">&
rhs)\n";
T tpart = m_t + rhs.m_t; //or whatever you want with the T parts
Foo<T,X+I> sum(tpart); //can't assign from *this as different
class unless X==I
return sum;
}
// // ..returning int:
// template<int X> int operator+(const Foo<T,X>& rhs){
// cout <<"In int Foo<T,"<<I<<">:
p+(Foo<T,"<<X<<">& rhs)\n";
// return size + X;
// }
};
int main(){
Foo<float, 2> float2(0.);
Foo<float, 3> float3(0.);
Foo<double,3> double3(0.);
//call usual op+
Foo<float,2> float2_2 = float2+float2;
cout << "float2 + float2 has Foo size: " <<float2_2.size<<'\n';
// //call int Foo<float,2>:
perator+<3>(const Foo<float,3>& rhs)
// int i23 = float2 + float3;
// cout << "float2 + float3 has value: " <<i23<<'\n';
//call Foo<float,2+3> Foo<float,2>:
perator+<3>(const Foo<float,3>&
rhs)
Foo<float,2+3> float23 = float2 + float3;
cout << "float2 + float3 has Foo size: " <<float23.size<<'\n';
// Can't do this in presence of usual op+ ..
// //try to call Foo<float,2+2> Foo<float,2>:
perator+<2>(const
Foo<float,2>& rhs)
// Foo<float,4> float4 = float2+float2; //Clashes with Foo<float,2>
Foo<float,2>:
p+(..)
// cout << "float2 + float2 has Foo size: " <<float4.size<<'\n';
return 0;
}