Named return values with templates
Kurt Garloff
garloff@student.physik.uni-dortmund.de
Thu Sep 4 11:06:00 GMT 1997
The Named return values feature, as described as in chapter 7.1 of the GCC
manual, does not work with templates. (This bug is in gcc-2.7.2,
pentium-gcc and egcs as well.)
See the following error messages produced by the compiler:
garloff@student:/home/garloff/numerix > egcc bug.cc
bug.cc: In function `class test<int> operator +(const class test<int>&,
const class test<int> &)':
bug.cc:25: no match for `test<T> & += const test<int> &'
bug.cc:15: candidates are: test<T>::operator +=(const test<T> &)
produced with the following source code:
garloff@student:/home/garloff/numerix > cat bug.cc
/* bug.cc */
/* simple program to demonstrate the bug with named return values in gcc
*/
/* (w) 4.9.97 by Kurt Garloff <K.Garloff@ping.de> */
#include <iostream.h>
// A simple numerical class
template <class T>
class test
{
T elem;
public:
test () { elem = 0; };
test (const T& a) { elem = a; };
test<T>& operator += (const test<T>& a) { elem += a.elem; return
*this; };
friend test<T> operator + (const test<T>&, const test<T>&);
friend ostream& operator << (ostream& os, const test<T>& a)
{ return os << a.elem; };
};
#ifndef NOBUG
// named return value version
template <class T>
test<T> operator + (const test<T>& a, const test<T>& b) return c(a);
{ c += b; };
#else
// equiv. version without named ret val
template <class T>
test<T> operator + (const test<T>& a, const test<T>& b)
{ test<T> c(a); c += b; return c; };
#endif
int main()
{
test<int> x, y;
x += 5; cout << x << endl;
y = x + 2; cout << y << endl;
}
The problem is that gcc/pgcc/egcs only partially replaces the type T with
int. The return value has type test<T> instead of test<int> and
therefore gcc looks for an operator test<T>::operator += (const
test<int>&) which is absolutely nonsense.
This does not happen, when the constructor test<T> c(a) is called within
the definition of the function and the named return value optimization is
not used (egcc bug.cc -DNOBUG).
I tried gcc-2.7.2.3 as well as gcc-2.7.2p-970522 and egcs-970901(2.90.04):
garloff@student:/home/garloff/numerix > egcc -v
Reading specs from /usr/local/lib/gcc-lib/i586-pc-linux-gnulibc1/egcs-2.90.04/specs
gcc version egcs-2.90.04 970901 (gcc2-970802 experimental)
They all have the same bug. I did not search for it in the gcc sources,
but I could if I get some hints ...
If somebody could fix this, I would be even more happy.
---
Kurt Garloff
<garloff@hft.e-technik.uni-dortmund.de>
More information about the Gcc-bugs
mailing list