如何在需要提及其他类的类中初始化变量,这些类需要循环声明?

Pos*_*elf 5 c++ circular-dependency c++11

在下面的例子中,struct Yfoward声明的前向声明是不够的.如果你注释掉X :: b,它编译得很好,因为Y有一个完整的结构声明可以使用,但X只有前向声明.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Ideone

以下是我可以提出的解决方案:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Ideone

虽然它在这个例子中起作用,但如果这些类是多态的,那么这将分别需要using X::X;或者using Y::Y;在这些类的子节点中.

有没有办法在头文件中执行此操作?

Hol*_*Cat 0

你可以这样做:

#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;
}
Run Code Online (Sandbox Code Playgroud)