验证多态向量元素的具体类型是否相同

Veryfing that concrete types of polymorphic vector elements are the same

我有一个抽象基础 class Type,它有多个具体子 class,例如 Type_boolType_intType_double等等 此外,我构造了两个 std::vector<Type*> 类型的向量,其中包含具体子 classes.

的对象

我已经实现了以下方法来检查这些向量是否相同。在这种情况下,相同意味着它们具有相同的大小,并且对于向量中的所有元素,它认为 type(v1[i]) == type(v2[i]) 对于所有 i=1,2, ... v1.size.

bool Env::areArgsTheSame(std::vector<Type*> containedFunArgs, std::vector<Type*> otherFunArgs)
{
    if(containedFunArgs.size() != otherFunArgs.size())
        return false;

    bool argsSame = true;
    for(std::size_t index = 0; index < containedFunArgs.size(); index++) {
        auto *arg = containedFunArgs[index];
        auto *otherArg = otherFunArgs[index];

        if(typeid(*arg) != typeid(*otherArg)){
            argsSame = false;
            break;
        }
    }

    return argsSame;
}

问题是,每当我用这些向量调用函数时,我都会遇到分段错误。多年来我一直试图解决这个问题,但似乎找不到办法。感谢任何帮助。

编辑: 我能够将错误缩小到 for 循环中的取消引用。但是我不知道访问具体类型的任何其他方法。

编辑2: 我以这种方式创建 containedFunArgsotherFunArgs

     Type_int *a, *b;
     Type_bool* c;

     std::vector<Type*> arguments = {a, b};
     std::vector<Type*> arguments2 = {a, c};

考虑代码...

Type_int *a, *b;
Type_bool* c;

std::vector<Type*> arguments = {a, b};
std::vector<Type*> arguments2 = {a, c};

指针 abc 未初始化。因此,当您在 Env::areArgsTheSame 中取消引用它们时,您会调用未定义的行为,这(至少在这种情况下)会导致段错误。

您的指针需要指向其关联类型的有效实例。所以你可以,例如,做...

Type_int a, b;
Type_bool c;

std::vector<Type*> arguments = {&a, &b};
std::vector<Type*> arguments2 = {&a, &c};

然后将 argumentsarguments2 传递给 Env::areArgsTheSame .