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; af(); return 0; } 

Compilation 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 main idea (using the derived class as the default value for the base-reference-type argument) works in visual studio, but not in g ++. I have to publish my code on a university server, where they compile it with gcc. What can I do? Is something missing?

+6
c ++ templates default-value g ++
source share
2 answers

You cannot create a (mutable) reference to an r-value. Try using the link constant:

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

Of course, you cannot change arg with a const reference. If you need to use a (mutable) link, use overloading.

  int f(base& arg) { ... } int f() { derived dummy; return f(dummy); } 
+7
source share

The problem you are facing is that you cannot use the default temporary argument for a function that uses a non-constant reference. Temporary persons cannot be associated with non-constant links.

If you do not modify the object inside, you can simply change the signature to:

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

If you are actually modifying the passed argument, you should use some other method that allows you to use optional arguments, the easiest of which is to use a pointer, which can be NULL by default.

+4
source share

All Articles