为什么我可以在C ++中的函数中定义结构和类? [英] Why can I define structures and classes within a function in C++?

查看:265
本文介绍了为什么我可以在C ++中的函数中定义结构和类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中错误地做了这样的事情,它工作。为什么我可以这样做?

I just mistakenly did something like this in C++, and it works. Why can I do this?

int main(int argc, char** argv) {
    struct MyStruct
    {
      int somevalue;
    };

    MyStruct s;
    s.somevalue = 5;
}

现在这样做后,我记得阅读关于这个秘诀的地方很久以前,作为一种穷人的C ++的功能编程工具,但我不记得为什么这是有效的,或我读它。

Now after doing this, I kind of remembered reading about this trick someplace, a long time ago, as a kind of poor-man's functional programming tool for C++, but I can't remember why this is valid, or where I read it.

欢迎对这两个问题的回答!

Answers to either question are welcome!

注意:虽然在写问题时我没有得到任何参考此问题,当前侧栏指出它,所以我'

Note: Although when writing the question I didn't get any references to this question, the current side-bar points it out so I'll put it here for reference, either way the question is different but might be useful.

推荐答案

幸运的是,下面提到的限制已经在C ++ 11中解除了,所以本地定义的类毕竟是有用的!感谢评论者bamboon。

: Happily, the restriction mentioned below has been lifted in C++11, so locally defined classes are useful after all! Thanks to commenter bamboon.

在本地定义类的能力会创建自定义函子(使用 )(),例如用于传递到 std :: sort()或loop bodies的比较函数,用于

The ability to define classes locally would make creating custom functors (classes with an operator()(), e.g. comparison functions for passing to std::sort() or "loop bodies" to be used with std::for_each()) much more convenient.

不幸的是,C ++禁止使用本地定义的类和模板

Unfortunately, C++ forbids using locally-defined classes with templates, as they have no linkage. Since most applications of functors involve template types that are templated on the functor type, locally defined classes can't be used for this -- you must define them outside the function. :(

相关报价从标准是:


14.3.1 / 2:。本地类型, ,未命名类型或从这些类型复合的类型不能用作模板类型参数的模板参数。

14.3.1/2: .A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

这篇关于为什么我可以在C ++中的函数中定义结构和类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆