Re: References to references
On 27/12/2011 23:07, Kelvin Chung wrote:
I'm getting an unforseen problem when I'm trying to compile code for
older compilers. The following code compiles in clang 3.0 on a Mac:
template <class Key>
struct Foo {
typedef Key& key_type;
virtual Bar mapKey(const key_type& key) = 0;
};
However, when I compile with gcc 4.1.2 on SUSE Linux, I get "cannot
declare reference to 'Key&', specifically wrt to mapKey().
I'm trying to find the root cause of this: Is it a C++11-specifc thing,
and thus barfing on gcc 4.1.2, which IIRC has no C++11 support? Is it
simply that I am expecting that "const key_type&" resolves to "Key&"
(ie. the references "collapse"), when it shouldn't? What should be the
workaround for getting this snippet to compile under gcc 4.1.2?
As a typedef only provides an alias for a type and there is no such
thing as a reference to a reference. Indeed a reference is essentially a
leaf type in that there are no further types based on a reference type.
Where there seems to be an extension of the type system it will actually
be a qualification of the type being referenced (e.g. when you cv
qualify a reference type you are in fact qualifying the underlying type.)
Now at some stage I think that templates have been provided with a
limited facility for dealing with references to reference types passed
in as template type arguments but this would not apply in your case.
Apart from academic experiment it is hard to see what you want to
achieve by code such as that in your example. As a broad guideline it is
best to avoid typedef'ing reference types as the consequences will
spring far too many unexpected errors.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]