避免使用带有虚方法的空基类构造函数

Bom*_*maz 4 c++ inheritance constructor initialization c++17

我有一个带有虚函数的空基类。有什么办法可以避免手动实现Derived的构造函数以便对其进行初始化?

struct Base
{
    virtual int f(int) const = 0;
    virtual ~Base() = 0; 
};

Base::~Base() {}

struct Derived: public Base
{
    int v;

    int f(int) const override{ return v;};
};

int main() 
{
    return Derived{5}.f(3);
}
Run Code Online (Sandbox Code Playgroud)

lub*_*bgr 5

有什么办法可以避免手动实现Derived的构造函数以便对其进行初始化?

Derived不可以。拥有基类和虚函数不会成为聚合。

如果删除这些virtual功能,则具有聚合,您可以

return Derived{{}, 5}.f(3);
//             ^^ explicitly initialize base class
Run Code Online (Sandbox Code Playgroud)

但这不是问题的重点,因此无法解决。