Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Implementing a function defined inside an anonymous structure

Tags:

c++

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.

like image 763
ZorbaTHut Avatar asked Feb 05 '12 01:02

ZorbaTHut


People also ask

Can functions be defined inside structure?

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result. Save this answer.

What is anonymous structure in C?

Anonymous unions/structures are also known as unnamed unions/structures as they don't have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions. Definition is just like that of a normal union just without a name or tag.

Can we have union inside structure?

A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.

What is the difference between union and anonymous union?

An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object. The member names of an anonymous union must be distinct from other names within the scope in which the union is declared.


1 Answers

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.

like image 181
Xeo Avatar answered Oct 09 '22 06:10

Xeo