C ++:实现在匿名结构中定义的函数 [英] C++: Implementing a function defined inside an anonymous structure
本文介绍了C ++:实现在匿名结构中定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下代码:
class Named {
class /*Unnamed*/ {
void Function();
} un;
};
// Implement Named::Unnamed::Function here
int main() {
Named named;
named.un.Function();
}
有没有任何方法来实现Named :: Unnamed :: Function未命名或嵌入函数的定义在Named的定义内?
Is there any way to implement Named::Unnamed::Function without either naming Unnamed or embedding the function's definition within the definition of Named?
我猜测答案是no,但GCC给了我有用的消息 Named :: {unnamed type#2} :: Function()',它发生在我可能有一些疯狂的语法。
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.
推荐答案
这实际上是可能的(在C ++ 11中),有两种方式:
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();
}
这可以感谢 $ 9.1 [class.name] p5
:
定义类类型或cv限定版本的 typedef-name (7.1.3)
这篇关于C ++:实现在匿名结构中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文