Suppose I have a class like this:
class Foo
{
std::vector<int> bar;
public:
std::vector<int>& get_bar() { return bar; }
};
and later on, I want another variable somewhere else that has the same type as bar. It would make sense to me if I could just do this:
decltype(Foo::bar) clone_of_bar;
But that doesn’t work. The compiler tells me ‘std::vector< int > Foo::bar’ is private.
So I end up having to use something like this:
std::remove_reference<decltype(std::declval<Foo>().get_bar())>::type clone_of_bar;
Which works, but looks like a complete mess. Maybe there’s an easier way to do it; I’m not really sure. But what I really want to know is why I can’t just use decltype(Foo::bar). Why should anyone care that bar is private? It’s not like I’m actually accessing the variable.
decltype is a new feature of the language. I just don’t understand why it was designed to not work on private variables.
In language lawyer terms,
baris a name, to use it in thedecltypeexpression the compiler has to do normal name lookup, which respects access control.Why should
decltypehave been designed differently to the rest of the language? You haven’t presented any convincing argument for why it shouldn’t be consistent with e.g.sizeof.As a class author, I don’t want you to be able to query private implementation details like that. If I wanted the type to be usable outside the class I’d define a public typedef telling you what type it is.
You want “another variable” that’s the same type as a private implementation detail? So if the author of class
Foorefactors their code and replaces the type with some other implementation detail, suddenly your code changes meaning and unrelated code might suddenly stop compiling or silently have different behaviour, because that code foolishly relied on private details that were none of its business. That would introduce coupling between private implementation details and unrelated code that the author ofFoomight not even know exists! That’s a terrible idea.