繁体   English   中英

C++ 是否有 std::vector 和普通 arrays 的超类?

[英]C++ Is there a superclass for std::vector and normal arrays?

我有两个结构,其中一个包含一个std::vector ,另一个包含一个普通array 我想知道他们是否有一个超类,以便我可以将两者都提供给 function:

struct A {
    float x;    // some variable that both should contain
    // Iterable<unsigned int> y;
};

template <unsigned int N>
struct A_array : A {
    unsigned int y[N];    // this should be the same
};

struct A_vector : A {
    std::vector<unsigned int> y;    // this should be the same
};

void func(struct A mystruct) {
    // access the vector/array
    mystruct.y[0]++;
}

在 Java 中,我猜这个超类可能类似于Iterable ?!

感谢您的帮助!

编辑:我添加了一个模板来使这个有效的 C++。

EDIT2:为了解决我能够通过任一struct的实际问题,我只是模板化了 function:

template <unsigned int N>
struct A_array {
    unsigned int y[N];    // this should be the same
};

struct A_vector {
    std::vector<unsigned int> y;    // this should be the same
};

template <typename S>
void func(S &mystruct) {
    // access the vector/array
    mystruct.y[0]++;
}

C++ 是否有 std::vector 和普通 arrays 的超类?

不,没有。 Arrays 不是类,所以它们首先不能有基类。

std::vector是一个 class 模板。 该标准没有为它定义任何基本 class 。 标准库可以使用基本 class,但这将是一个实现细节。

此外,不可能“覆盖”基础 class 的数据成员。


尽管动态多态是一种选择,但我们经常希望在 C++ 中避免它的开销。 Static多态性是通过模板和概念实现的。 类似于 Java 的Iterable的 C++ 概念是range概念。

数组和向量都符合range概念,因此如果您允许公共访问它们 - 正如您在示例中所做的那样 - 那么模板可以以统一的方式使用它们。

如果您希望进行一些封装并保持成员私有,您可以使 class 本身符合range概念。 为此,您的 class 应提供成员函数beginend ,它们将迭代器返回到第一个元素并在最后一个元素之后返回哨兵。

您的示例使用的是下标运算符,这不是保证range支持的东西。 没有要求它的标准概念。 这不一定是问题。 概念大多是可选的,尽管它们通常有助于编写正确的程序。

也就是说,您可以定义自己的概念,也可以将用法更改为以下形式:

// mystruct.y[0]++;
(*std::begin(mystruct.y))++;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM