Search code examples
c++lambdastaticstatic-methods

C++ static members initialized with lambda


Following is legal:

class FooAccesor {
  static std::function<void(Foo& foo)> getFooMethod() {
    return []() { foo.method(); };
  }
}

while

class FooAccesor {
  static const std::function<void(Foo& foo)> fooMethod = []() { foo.method(); };
}

is not. (Tried to fix with constexpr to no avail.) My MSVC compiler explained that member of type const std::function<void(Foo& foo)> cannot have in-class initializer. So I have to do something like

class FooAccesor {
  static std::function<void(Foo& foo)> fooMethod;
}
std::function<void(Foo& foo)> fooMethod = []() { foo.method(); };

My question is: why am I allowed to effectively initialize a method, while (as far as I can tell) I am not allowed to initialize static datamember?


Solution

  • You are allowed to declare the member as inline (since C++17). And you have to fix several typos in your example (missing ; and not passing a Foo to the lambda):

    #include <functional>
    
    struct Foo { void method(){}};
    
    class FooAccesor {
      inline static std::function<void(Foo& foo)> fooMethod = [](Foo& foo) { foo.method(); };
    };