为什么我可以在 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 中取消,因此在本地定义的类毕竟有用!感谢评论家bambons.
: Happily, the restriction mentioned below has been lifted in C++11, so locally defined classes are useful after all! Thanks to commenter bamboon.
在本地定义类的能力将创建自定义函子(带有 operator()()
的类,例如用于传递给 std:: 的比较函数)sort()
或循环体"与 std::for_each()
一起使用更方便.
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.
相关文章