bcf
bcf

Reputation: 2134

Redefining Friend Function of Base Class in Derived Class

I want to redefine the operator* function that is originally defined as a friend in the Vector class, in a derived class, BigNum. Specifically I want to call the Vector version of operator* and then do some other things to the result of that operation in BigNum's operator*. Here's a snippet of the structure (thanks again to @lemmes for helping with this):

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

public:                                                                                                                 
  Vector();                                                                                                                        
  Vector(const std::vector<T> vec);                                                                                                
  Vector(const Vector& vec);

  template<typename T1, typename T2>
  friend auto operator*(const Vector<T1>& lhs, const Vector<T2>& rhs) -> Vector<decltype(std::declval<T1>() * std::declval<T2>())>;
};

template<typename T1, typename T2>
auto operator*(const Vector<T1>& lhs, const Vector<T2>& rhs) -> Vector<decltype(std::declval<T1>() * std::declval<T2>())>
{
  typedef decltype(std::declval<T1>() * std::declval<T2>()) T3;
  assert(lhs.base.size() == rhs.base.size());
  Vector<T3> result;
  result.base.reserve(lhs.base.size());
  std::transform(lhs.base.begin(), lhs.base.end(), rhs.base.begin(), std::back_inserter(result.base),
                 [](const T1& e1, const T2& e2) { return e1 * e2; });
  return result;
}

class BigNum : public Vector<int>
{
 public:
  BigNum();
  BigNum(const std::vector<int> init);
  ~BigNum();

  BigNum operator*(const BigNum& rhs);
};
#endif

BigNum BigNum::operator*(const BigNum& rhs)
{

  // How can I call Vector's operator* (a friend of the Vector class)                                                                            
  // and then do other stuff in here?                                                                                                            
}

#include "BigNum.h"

int main()
{

  int arr1[] = {1,2,3,4,5};
  int arr2[] = {10,20,30,40,50};
  std::vector<int> vec1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]));
  std::vector<int> vec2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]));

  BigNum bn1(vec1), bn2(vec2);

  bn1 * bn2;  // want to call BigNum's operator* here

  return 0;
}

I obviously can't do something like Vector::operator* since it's a friend. Thanks in advance!

Upvotes: 0

Views: 227

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477680

You can write static_cast<Vector<int>&>(bn1) * static_cast<Vector<int>&>(bn2) to have the vector's overloaded operator called.

Upvotes: 1

Related Questions