Are there any “penalties” for defining a struct inside a function?

In C++11, no – there’s no penalty. I would even consider it a very good style to not pollute any “more visible” scopes with you implementation details, unless, of course, you want to reuse that functor elsewhere. However, lambdas are essentially a condensed form of this idea, and should usually be preferred if you are just using the struct as functor. For all kinds of data, it is perfectly fine, although it usually competes with std::pair and std::tuple in that aspect.

In C++03, you cannot use such a struct as a template parameter, since those parameters need to have external linkage (Visual Studio lets you do it anyways, though). It can still be useful to use such a struct with a polymorphic interface.

Leave a Comment

tech