【问题标题】:Can unnamed structures inherit?未命名的结构可以继承吗?
【发布时间】:2014-06-01 12:18:04
【问题描述】:

以下看起来像是编译错误:

struct : Base { };

然而,当used [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] 免责声明:我并没有假装提供的示例很有用。我很少使用未命名的结构,当我这样做时,它们通常会捆绑一些内置的成员变量,以便为类提供更清晰的接口。问题来自memberspaces不需要命名结构的观察

【问题讨论】:

  • 第二个例子是有效的。它的用途?尚未确定。
  • @StoryTeller: ideone.com/CWXUkv
  • @lorro 哇,很复古。巧妙的技巧,但 std::tie 是 IMO 更好的方法。
  • @StoryTeller:我不太喜欢 std::tie,因为它要求您首先构造一个可能无效的对象。如果它是资源怎么办,如果我们没有默认构造函数怎么办,如果构建需要时间/分配怎么办?换句话说,我希望有一天我们可以在任何地方声明变量,包括在 std::tie 内部(或 make tie)。不会比里面的 for / if / while... 更糟了……
  • @lorro, Rejoice,这似乎已经变成了 C++17 open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0144r0.pdf

标签: c++ inheritance struct unnamed-class


【解决方案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

Demo on ideone.

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-04-04
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 2018-03-28
      相关资源
      最近更新 更多