about return type of an overloaded operator

B

benben

Given a class template Vector<>, I would like to overload operator +.
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:


template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);


Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.

Currently I am defaulting U_or_V just to U. But this has some subtle
implications. For example, the breach of the commutative law:

Vector<int> vi(0, 0, 0);
Vector<double> vd(1.1, 1.2, 1.3);

assert((vi + vd) == (vd + vi));

The above innocent code may not even compile depending on how operator==
is declared. If it did, it is again up to the details of operator== to
decide whether the assertion would succeed or fail. Ideally, both
addition expressions should give Vector<double> because (int() + double
()) is a double.

Any thought will be appreciated!

Ben
 
S

Shark

The above innocent code may not even compile depending on how operator==
is declared. If it did, it is again up to the details of operator== to
decide whether the assertion would succeed or fail. Ideally, both
addition expressions should give Vector<double> because (int() + double
()) is a double.

if you are faced with a dilemma like this, consider how C++'s double
and int may behave in this situation. That helps keep code consistent
and you don't have to parse your mental design each time. Scott Meyer's
book Effective C++ has some insights on overloading. Try it at your
local B&N or Borders.

My 0.000002 cents!
 
B

benben

if you are faced with a dilemma like this, consider how C++'s double
and int may behave in this situation. That helps keep code consistent
and you don't have to parse your mental design each time. Scott Meyer's
book Effective C++ has some insights on overloading. Try it at your
local B&N or Borders.

Thanks for your advices!

As to your first advice, please see that I did make an effort to keep
the semantic consistent with that with C++'s native types. This is
exactly why I want:

// pseudo C++ code
template <typename U, typename V>
Vector<typeof(U()+V())> operator+ (
const Vector<U>&,
const Vector<V>&);

My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.

I will seriously consider your second advice.

Yours,
Ben
 
S

Shark

benben said:
Thanks for your advices!

As to your first advice, please see that I did make an effort to keep
the semantic consistent with that with C++'s native types. This is
exactly why I want:

// pseudo C++ code
template <typename U, typename V>
Vector<typeof(U()+V())> operator+ (
const Vector<U>&,
const Vector<V>&);

My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.

Ok, I'm a beginner too since the last 4 years or so!

How about you declare an abstract base class B from which U and V
derive, and in operator+ you can have a factory design pattern return
the appropriate type.

Once you have the type returned, you can then overload == to accept
parameters of type base B, which will therefore work in all cases, and
can do comparisons too. I think this should work.

Form wikipedia this is a sample factory pattern:

#include <memory>
using std::auto_ptr;

class Control { };

class PushControl : public Control { };

class Factory {
public:
// Returns Factory subclass based on classKey. Each
// subclass has its own getControl() implementation.
// This will be implemented after the subclasses have
// been declared.
static auto_ptr<Factory> getFactory(int classKey);
virtual auto_ptr<Control> getControl() const = 0;
};

class ControlFactory : public Factory {
public:
virtual auto_ptr<Control> getControl() const {
return auto_ptr<Control>(new PushControl());
}
};

auto_ptr<Factory> Factory::getFactory(int classKey) {
// Insert conditional logic here. Sample:
switch(classKey) {
default:
return auto_ptr<Factory>(new ControlFactory());
}
}
 
A

Alf P. Steinbach

* benben:
My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.

Consider something like

template< unsigned Id > struct IdToType;
template<> struct IdToType<1> { typedef char T; };
template<> struct IdToType<2> { typedef unsigned char T; };
...

template< typename T > struct TypeToId;
template<> struct TypeToId<char> { enum{ id = 1 }; };
...

template< unsigned Id > struct MyTypeId { char sizer[Id]; };

template< typename T > MyTypeId< TypeToId<T>::id > typeOfArg( T );

template< typename U, typename V >
typename IdToType<sizeof(typeOfArg(U()+V()).sizer)>::T
operator+( U const& u, V const& v )
{
...
}

I don't know whether it'll work as written.

But I think it better that you use the time to check it all out with a
compiler, than that I should do that... ;-)
 
S

Shark

Shark said:
How about you declare an abstract base class B from which U and V
derive, and in operator+ you can have a factory design pattern return
the appropriate type.

I forgot to add, that B should be a wrapper around your types. It makes
sense to me, if I understand the problem correctly.
 
J

John Carson

benben said:
Given a class template Vector<>, I would like to overload operator +.
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:


template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);


Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.

Currently I am defaulting U_or_V just to U. But this has some subtle
implications. For example, the breach of the commutative law:

Vector<int> vi(0, 0, 0);
Vector<double> vd(1.1, 1.2, 1.3);

assert((vi + vd) == (vd + vi));

The above innocent code may not even compile depending on how
operator== is declared. If it did, it is again up to the details of
operator== to decide whether the assertion would succeed or fail.
Ideally, both addition expressions should give Vector<double> because
(int() + double ()) is a double.

Any thought will be appreciated!

Ben

The obvious, though somewhat laborious, solution is to specialize the
template for particular (U,V) combinations. Make U the return type in the
general case, and make it V (or perhaps something else --- say complex if U
is real and V is imaginary) for the special cases that need it.

Thus you have the general:

template <class U, class V>
Vector<U> operator+ (const Vector<U>&, const Vector<V>&);

and the specialized:

template <>
Vector<double> operator+ (const Vector<int>&, const Vector<double>&);


Somewhat more elegant would be to define an extra class to indicate the
return type. You can make that class depend on U and V. First we define
the usual case where Vector<U> is satisfactory as the return type.

template<class U, class V>
struct ReturnType
{
typedef Vector<U> type;
};

You can then specialize this for mixed cases that need special handling,
e.g.,

template<>
struct ReturnType<int, double>
{
typedef Vector<double> type;
};


To illustrate its use, consider:


#include <iostream>
using namespace std;

template<class T>
class Vector;

template<class U, class V>
struct ReturnType
{
typedef Vector<U> type;
};

template<>
struct ReturnType<int, double>
{
typedef Vector<double> type;
};


template<class T>
class Vector
{
T array[3];
public:
template<class U, class V>
friend typename ReturnType<U,V>::type
operator+(const Vector<U>&, const Vector<V>&);
Vector()
{
array[0]=T();
array[1]=T();
array[2]=T();
}
Vector(T first, T second, T third)
{
array[0] = first;
array[1] = second;
array[2] = third;
}
T operator[](int index) const
{
return array[index];
}
T &operator[](int index)
{
return array[index];
}
};

template <class U, class V>
typename ReturnType<U,V>::type
operator+(const Vector<U>&lhs, const Vector<V>&rhs)
{
typename ReturnType<U,V>::type sum;
sum[0] = lhs[0]+rhs[0];
sum[1] = lhs[1]+rhs[1];
sum[2] = lhs[2]+rhs[2];
return sum;
}

int main()
{
Vector<int> i(4,2,5);
Vector<double> d(1.2, 2.4, 7.2);

Vector<double> result = i+d;

cout << result[0] << ',' << result[1] << ',' << result[2] << '\n';
return 0;
}
 
A

andy

benben said:
Given a class template Vector<>, I would like to overload operator +.
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:


template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);


Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.

Seriously take a look at Boost.Typeof typeof emulation in the latest
version of the boost libraries. It is very comprehensive and great for
just this situation.

Useage would be something like:

template <typename U, typename V>
Vector< BOOST_TYPEOF_TPL(U() + V())> operator+ (
const Vector<U>&,
const Vector<V>&);

You may have to do some work to 'register' U and V though Boost.Typeof
can make use of compiler extensions in some cases too. 'registration'
is covered in the documentation. There are some differences between use
with templates and non_templates too, but its probably the nearest to
true language support.

Check it out.

regards
Andy Little
 
B

benben

Alf said:
* benben:
My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.


Consider something like

template< unsigned Id > struct IdToType;
template<> struct IdToType<1> { typedef char T; };
template<> struct IdToType<2> { typedef unsigned char T; };
...

template< typename T > struct TypeToId;
template<> struct TypeToId<char> { enum{ id = 1 }; };
...

template< unsigned Id > struct MyTypeId { char sizer[Id]; };

template< typename T > MyTypeId< TypeToId<T>::id > typeOfArg( T );

Thanks for your reply alf! But I am very confused with the code,
especially the line immediately above.
template< typename U, typename V >
typename IdToType<sizeof(typeOfArg(U()+V()).sizer)>::T
operator+( U const& u, V const& v )
{
...
}

I don't know whether it'll work as written.

It will take some time before I can fully digest the code above. I am
under the impression this method relies on type size to work out the
resultant type. Please pardon my impoliteness but I don't see the above
could select, for example, double from a int-double pair.
But I think it better that you use the time to check it all out with a
compiler, than that I should do that... ;-)

Thank you! I will.

Ben
 
A

Alf P. Steinbach

* benben:
Alf said:
* benben:
My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.


Consider something like

template< unsigned Id > struct IdToType;
template<> struct IdToType<1> { typedef char T; };
template<> struct IdToType<2> { typedef unsigned char T; };
...

template< typename T > struct TypeToId;
template<> struct TypeToId<char> { enum{ id = 1 }; };
...

template< unsigned Id > struct MyTypeId { char sizer[Id]; };

template< typename T > MyTypeId< TypeToId<T>::id > typeOfArg( T );

Thanks for your reply alf! But I am very confused with the code,
especially the line immediately above.

It's meant to be a function, not implemented anywhere, returning a
struct where the size of that struct's 'sizer' identifies the argument
type. This struct is then passed to sizeof (so that the function is
never actually called), the result of sizeof used to obtain the type
from TypeToId mapping. The point being that you only have to define
O(n) type mapping classes for n supported types, instead of O(n^2).
 
B

benben

Shark said:
I forgot to add, that B should be a wrapper around your types. It makes
sense to me, if I understand the problem correctly.

Thank you shark!

The challenge is, I can't insert a base class for U and V because they
can be anything from built-in types (int, double, char, etc) to types
that must not exhibit virtuality (hence must not have an abstract base.)

It is possible though, as you have reminded me, to design a secondary
type to hold the operands temporarily and only evaluate the result
against a certain type upon assignment.

But this will render the orginal design far more complex and much less
maintainable.

Anyway your help was much appreciated!

Ben
 
O

owl ling

this is good idea.....but there are a problem, RTTI(as "typeof") is a
technique for run-time. but the template argument be sure in
complier-time...
 
B

benben

Thank you John for the time and effort in your reply! I much appreciated.

I did considered using a traits class. I can put my effort in and give
all the specializations necessary for built-in types. But as the vector
class also takes class types it is required of the USER of the vector
class to provide specializations of whatever custom type they use.
Whether the user remembers (or cares) to give a specialization would
have an implication on the semantic, which can be subtle. And this holds
me back from using a traits class to determine the return type.

Yours,
Ben
 
E

Earl Purple

template <typename U, typename V>
Vector< BOOST_TYPEOF_TPL(U() + V())> operator+ (
const Vector<U>&,
const Vector<V>&);

You may have to do some work to 'register' U and V though Boost.Typeof
can make use of compiler extensions in some cases too. 'registration'
is covered in the documentation. There are some differences between use
with templates and non_templates too, but its probably the nearest to
true language support.

Check it out.

regards
Andy Little

Much that I appreciate the contributions of boost, I just hope that all
these macros never make the standard.

The best I could come up with, that compiles and runs correctly is
this:

#include <algorithm>
#include <iostream>
#include <vector>

template < typename T >
class Vector
{
private:
typedef std::vector< T > vec_type;

std::vector< T > realVec;
public:
typedef typename vec_type::const_iterator const_iterator;
typedef typename vec_type::size_type size_type;

void reserve( size_type sz )
{
realVec.reserve( sz );
}

size_type size() const
{
return realVec.size();
}

const_iterator begin() const
{
return realVec.begin();
}

const_iterator end() const
{
return realVec.end();
}

void push_back( const T& t )
{
return realVec.push_back( t );
}
};

template < typename U, typename V, typename W >
Vector<W> vecSum( const Vector<U> & uvec, const Vector<V> & vvec, W w )
{
Vector<W> wvec;
typename Vector<U>::const_iterator uIter = uvec.begin();
typename Vector<U>::const_iterator uEnd = uvec.end();
typename Vector<V>::const_iterator vIter = vvec.begin();

wvec.reserve( uvec.size() );
while ( uIter != uEnd )
{
wvec.push_back( *uIter + *vIter );
++uIter;
++vIter;
}
return wvec;
}

template < typename T >
void outputVec( const Vector<T> & t )
{
std::copy( t.begin(), t.end(), std::eek:stream_iterator< T >(
std::cout, "\n" ) );
}

template < typename U, typename V >
void outputVecSum( const Vector<U> & uvec, const Vector<V> & vvec )
{
outputVec( vecSum( uvec, vvec, U() + V() ) );
}

int main()
{
Vector< int > uvec;
Vector< double > vvec;

uvec.push_back( 1 );
uvec.push_back( 2 );
uvec.push_back( 3 );

vvec.push_back( 1.5 );
vvec.push_back( 2.5 );
vvec.push_back( 3.5 );

outputVecSum( uvec, vvec );
}

Note I made every effort never to work out what type W would be (thus
outputVec and outputVecSum as templates).
 
S

Shark

template said:
Vector<W> vecSum( const Vector<U> & uvec, const Vector<V> & vvec, W w )

Note I made every effort never to work out what type W would be (thus
outputVec and outputVecSum as templates).

this is cool, but to get a sum, we have to pass a 3rd argument, right?
So basically we cannot implement operator= without using a 3rd
parameter in these terms?
 
S

Shark

template said:
Vector<W> vecSum( const Vector<U> & uvec, const Vector<V> & vvec, W w )

Note I made every effort never to work out what type W would be (thus
outputVec and outputVecSum as templates).

this is cool, but to get a sum, we have to pass a 3rd argument, right?
So basically we cannot implement operator= without using a 3rd
parameter in these terms?
 
A

andy

Earl said:
Much that I appreciate the contributions of boost, I just hope that all
these macros never make the standard.

Boost.Typeof cant be anything but a macro for now. AFAIK The author is
fully aware that its only standing in for proper language support. IOW
its a macro exactly because the facilities it provides are not in the
standard. Notwithstanding that its a masterpiece IMO. Unfortunately it
is only available from boost cvs at the monent. I'm not sure if it
will make the next boost distro or not, but I hope it does.

regards
Andy Little
 
M

michael.fawcett

I didn't check CVS, but the file I'm currently using has this in the
comments so it sounds like what Andy is talking about.

"Return Type Deduction
[JDG Sept. 15, 2003]

Before C++ adopts the typeof, there is currently no way to deduce the
result type of an expression such as x + y. This deficiency is a major
problem with template metaprogramming; for example, when writing
forwarding functions that attempt to capture the essence of an
expression inside a function."

I use it for the exact same purpose as the OP like so:

template <typename T0, typename T1>
typename boost::result_of_plus<vec3<T0>, vec3<T1> >::type
operator+(vec3<T0> lhs, const vec3<T1> &rhs);

which is slightly different than your usage, but only because I
specialized the result_of struct on my type. I too hope this makes it
into the next boost distro.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top