Re: Question regarding use of C++0x auto keyword
<markfrey@fastmail.fm> writes:
I have occasionally written classes like this (massively simplified):
class myclass
{
private:
struct converter
{
converter(int n) : n_(n) { /*empty*/ }
operator int() { return(n_); }
};
public:
converter getSomething() { return(converter(5)); }
};
int main()
{
myclass mc;
int n = mc.getSomething();
return(0);
}
now, say we change main() to use the auto keyword as follows:
int main()
{
myclass mc;
auto n = mc.getSomething();
return(0);
}
The local 'n' is now of type struct converter. When I compile this
using the Comeau test drive compiler it compiles without complaint.
Should it? It seems to me that auto should just cause the compiler
to determine the type of the expression "mc.getSomething()" but that
it then should compile as if 'auto' were replaced by that type and
so the compile should generate an error because 'struct converter'
is not accessible (being private).
The type cannot be explicitly named (being private), but it can be
accessed. In particular, you can pass an object of a private type to a
function template and it will correctly deduce and use the private type.
template<typename T>
void f(T t)
{
}
int main()
{
myclass mc;
f(mc.getSomething()); // T deduces to be myclass::converter
}
This works even in C++03.
The new auto keyword is specified to behave exactly the same as the
deduction of T in the function template example, so the type is deduced
to be myclass::converter. Since the copy constructor is public, it is
accessible to main, and your original example is fine.
Anthony
--
Author of C++ Concurrency in Action | http://www.manning.com/williams
just::thread C++0x thread library | http://www.stdthread.co.uk
Just Software Solutions Ltd | http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]