2

I have a function named return_local where it returns an instance of a local class enclosed with a lambda.

auto return_local() {
  return [] {
    static int sample { 5 };
    struct Point {
      int x, y;
      int show_sample() { return sample; }
    };
    return Point {};
  }();
}
using Point = decltype(return_local());

Now, I can use Point as alias with characteristics of local classes.

Point p {.x = 4, .y = 1};
p.show_sample(); // returns 5

Is this code normal? Are there any benefits of using this "leaked" class?

Desmond Gold
  • 1,517
  • 1
  • 7
  • 19
  • 3
    You can do that, but it's not clear why you would want to. Why not just define `Point` at namespace scope? – Igor Tandetnik Jul 25 '21 at 03:30
  • 2
    It's a bit unusual, but the code is within the bounds of what I'd consider normal. I don't see any benefits to coding this way over declaring Point on its own and having the sample be a class static variable. The downside, as I see it, is it is more cognitive load for maintenance. – Eljay Jul 25 '21 at 03:30
  • 3
    This is sometimes called a "Voldemort Type" (A type that shall not be named). –  Jul 25 '21 at 03:57

0 Answers0