Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

derived class as default argument g++

Please take a look at this code:

template<class T>
class A
{
 class base
 {

 };

 class derived : public A<T>::base
 {

 };

public:

 int f(typename A<T>::base& arg = typename A<T>::derived())
 {
  return 0;
 }
};

int main()
{
 A<int> a;
 a.f();
 return 0;
}

Compiling generates the following error message in g++:

test.cpp: In function 'int main()':
test.cpp:25: error: default argument for parameter of type
                    'A<int>::base&' has type 'A<int>::derived'

The basic idea (using derived class as default value for base-reference-type argument) works in visual studio, but not in g++. I have to publish my code to the university server where they compile it with gcc. What can I do? Is there something I am missing?

like image 575
Vincent Avatar asked Apr 16 '10 13:04

Vincent


1 Answers

You cannot create a (mutable) reference to an r-value. Try to use a const-reference:

 int f(const typename A<T>::base& arg = typename A<T>::derived())
//     ^^^^^

Of course you can't modify arg with a const-reference. If you have to use a (mutable) reference, use overloading.

 int f(base& arg) {
   ...
 }
 int f() {
   derived dummy;
   return f(dummy);
 }
like image 171
kennytm Avatar answered Sep 28 '22 17:09

kennytm