5

Given the following code:

class Named {
  class /*Unnamed*/ {
    void Function();
  } un;
};

// Implement Named::Unnamed::Function here

int main() {
  Named named;
  named.un.Function();
}

Is there any way to implement Named::Unnamed::Function without either naming Unnamed or embedding the function's definition within the definition of Named?

I'm guessing the answer is "no", but GCC gives me the useful message "undefined reference to `Named::{unnamed type#2}::Function()', and it occured to me there might be some crazy possible syntax.

ZorbaTHut
  • 1,163
  • 1
  • 11
  • 19
  • 1
    Did you see http://stackoverflow.com/questions/991062/passing-unnamed-classes-through-functions ? – whtlnv Feb 05 '12 at 01:31
  • 2
    There isn't going to be "some crazy syntax". Obviously the compiler will assign some sort of name to every entity, but those are not knowable or usable. I'd say that an out-of-line definition requires the name of a function (with the exception of constructors), and since you cannot name the function, you cannot define it out of line. – Kerrek SB Feb 05 '12 at 01:39
  • @whitelion: I didn't, but it's kind of irrelevant to the question. Yes, there are certainly many ways to work *around* the problem - I mean, one obvious one is just to name the class - I'm simply curious if there's a way to avoid the workarounds. – ZorbaTHut Feb 05 '12 at 01:40

1 Answers1

15

This is actually possible (in C++11), and in two ways:

struct Named {
  struct /*Unnamed*/ {
    void Function();
  } un;
  typedef decltype(un) Unnamed;
};

// #1
void Named::Unnamed::Function(){
}

//// #2
//typedef decltype(Named::un) Unnamed;
//void Unnamed::Function(){
//}
//// same way, using template alias
//template<class T> using alias = T;
//void alias<decltype(Unnamed::un)>::Function(){
//}

int main() {
  Named named;
  named.un.Function();
}

Live example on Ideone.

This is possible thanks to $9.1 [class.name] p5:

A typedef-name (7.1.3) that names a class type, or a cv-qualified version thereof, is also a class-name.

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • Classy! Not an approach I would have thought of. Unfortunately I'm not using a C++11-capable compiler, but you definitely deserve credit for the solution :) – ZorbaTHut Feb 05 '12 at 18:33