I have a class, with a variadic template member function that attempts to expand a fold expression inside of a lambda. I think it is easier to explain with a minimal example.
struct GameState {
using SystemFunc = std::function<void()>;
std::vector<SystemFunc> m_systems;
template <typename ComponentType>
bool getComponent() const {
return true;
}
template<typename... Components>
void registerSystem() {
m_systems.push_back([this]() {
auto value = (getComponent<Components>() && ...);
});
}
};
This fails to compile with error C2662 ‘bool GameState::getComponent(void)’: cannot convert ‘this’ pointer from ‘GameState::registerSystem::<lambda_1>’ to ‘GameState &’ (on MSVC).
The error suggests this has something to do with const-correctness. I have tried every combination of ‘getComponent()’ being const/non-const and adding ‘mutable’ to the lambda. Making ‘registerSystem()’ const fails with a different error.
I have found a way to accomplish what I want using c++23’s deducing auto, however, I was curious why this doesn’t work.
Shea Harrington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.