Temple
Temple

Reputation: 1631

Pass by reference in templated class

Code below:

#include <iostream>
#include <cmath>

template<class T>
class Number {
private:
 T val;
public:
 Number(T& tRefArg) : val(tRefArg) {}
 void print() {
  std::cout << val << std::endl;
 }
};

template<class R>
class RoundedNumber : public Number<R> {
public:
 R val;
public:
 RoundedNumber(R& tRefArg): Number<R>(tRefArg), val(tRefArg) {
  val = floor(val + 0.5f);
 }
 void print() {
  std::cout << val << std::endl;
 }
};

int main() {
 int i = 8;
 Number<double>* myNumber = new RoundedNumber<double>(i);
}

Gives error:

2.cpp:30:56: error: invalid initialization of non-const reference of type ‘double&’ from an rvalue of type ‘double’ Number* myNumber = new RoundedNumber(i);

I assume it is treated as rvalue but why?

Upvotes: 1

Views: 54

Answers (1)

skypjack
skypjack

Reputation: 50550

Member functions expect a double, you are providing an int. A temporary double is created from the int and you cannot bind a temporary to a reference, but you can bind it to a const reference.
That is, you can use this:

Number(const T& tRefArg) : val(tRefArg) {}

Or this:

Number(T tRefArg) : val(tRefArg) {}

And this:

RoundedNumber(const R& tRefArg): Number<R>(tRefArg), val(tRefArg) {

Or this:

RoundedNumber(R tRefArg): Number<R>(tRefArg), val(tRefArg) {

Upvotes: 3

Related Questions