How to initialize variables in classes that require the mention of other classes that require circular declarations?

In the following example, the front declaration declaration of struct Y fooward is not enough. If you comment out X :: b, it compiles fine, since Y has a complete declaration of the structure to work with, but X has only a forward declaration.

 #include <functional> #include <iostream> struct Y; struct X { std::function<bool(Y&)> b{[] (auto& y_) { return y_.a; }}; bool a{false}; }; struct Y { std::function<bool(X&)> b{[] (auto& x_) { return x_.a; }}; bool a{true}; }; int main() { return 0; } 

Ideone

Below is a fix I could come up with:

 #include <functional> #include <iostream> struct Y; struct X { X(); std::function<bool(Y&)> b; bool a{false}; }; struct Y { Y(); std::function<bool(X&)> b{[] (auto& x_) { return x_.a; }}; bool a{true}; }; X::X() : b([] (auto& y_) { return y_.a; }) {} Y::Y() : b([] (auto& x_) { return x_.a; }) {} int main() { return 0; } 

Ideone

And although it works in this example, if the classes were polymorphic, children of these classes would need to use using X::X; or using Y::Y; .

Is there a way to do this in the header files themselves?

+5
source share
1 answer

You can do it:

 #include <functional> template <typename T> bool (*get_lambda())(T&) {return [] (auto& y_) { return y_.a; };}; struct Y; struct X { std::function<bool(Y&)> b{get_lambda<Y>()}; bool a{false}; }; struct Y { std::function<bool(X&)> b{get_lambda<X>()}; bool a{true}; }; int main() { return 0; } 
0
source

Source: https://habr.com/ru/post/1270598/


All Articles