未命名的结构可以继承吗?

Can unnamed structures inherit?

本文关键字:继承 结构 未命名      更新时间:2023-10-16

下面的代码看起来像是编译错误:

struct : Base { };

然而,当使用[1]时,它似乎有效:

#include <iostream>
using namespace std;
template<bool B>
struct A 
{
    struct : std::integral_constant<bool, B> {
    } members;
};
int main()
{
    A<true> a;    
    cout << a.members.value << endl;
    return 0;
}

在c++中,未命名的结构继承是有效的吗?有什么有用的例子吗?


[1] 免责声明:我不是假装提供的示例是有用的。我很少使用未命名的结构,当我这样做时,它们通常捆绑在一起一些内置的成员变量,以便为类提供一个更清晰的接口。这个问题来自于观察到成员空间不需要命名为结构

未命名的类可以继承。这很有用,例如,在必须继承才能覆盖虚函数的情况下,但永远不需要一个以上的类实例,也不需要引用派生类型,因为对基类型的引用就足够了。

下面是一个例子:

#include <iostream>
using namespace std;
struct Base {virtual int process(int a, int b) = 0;};
static struct : Base {
    int process(int a, int b) { return a+b;}    
} add;
static struct : Base {
    int process(int a, int b) { return a-b;}    
} subtract;
static struct : Base {
    int process(int a, int b) { return a*b;}    
} multiply;
static struct : Base {
    int process(int a, int b) { return a/b;}    
} divide;
void perform(Base& op, int a, int b) {
    cout << "input: " << a << ", " << b << "; output: " << op.process(a, b) << endl;
}
int main() {
    perform(add, 2, 3);
    perform(subtract, 6, 1);
    perform(multiply, 6, 7);
    perform(divide, 72, 8);
    return 0;
}

这段代码创建了Base的四个匿名派生——每个操作一个。当这些派生的实例被传递给perform函数时,将调用适当的覆盖。需要注意的是,perform不需要知道任何具体的类型——基本类型和它的虚函数就足够完成这个过程了。

下面是运行上述代码的输出:
input: 2, 3; output: 5
input: 6, 1; output: 5
input: 6, 7; output: 42
input: 72, 8; output: 9

你的第一个例子,因为它没有声明任何东西,显示了一个匿名结构的尝试(这是不允许的- 7/3),而不是一个未命名的(这是)。

c++ 11标准的9/1中的语法似乎允许未命名的类有一个基,所以我认为你的第二个例子是好的。