Re: References to references
On Dec 28, 12:07 am, 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().
First of all, using a reference as key type in something like std::map
won't work. This is not how it's done in C++.
Secondly, there are no references to references. But in C++11 there is
something called "reference collapsing".
const key_type& --> key_type&
The const will be silently ignored because a reference is inherently
const and the additonal & will also be ignored because of reference
collapsing. "& + & = &", so to speak.
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?
Yes. Reference collapsing is specific to C++11. I don't know whether
gcc 4.1.2 has any C++11 support. Anyhow, you would have to enable it
explicitly.
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?
That depends on what you are actually trying to do. Your approach
looks very unusual. Unless you explain your goals, it's hard to
suggest anything helpful.
Of course, you could simply write your own type-transforming traits
class to emulate this C++11 behaviour.
template<class T> struct id {typedef T type;};
template<class T> struct bar : id<const T&> {};
template<class T> struct bar<T&> : id<T&> {};
:::
typename bar<T>::type instead of const T&
But I doubt that this is actually a good idea in your case.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]