c++ - 在 C++ 中使用成员函数 vector 时,有没有办法实现协变返回类型?

标签 c++ inheritance vector stdvector covariant-return-types

我的基类看起来像(当然有构造函数):

class gBase
{
public:
    // The user will implement a vector of a vector of functions that can be called as g[i][alpha](k)
    virtual vector<cdouble (gBase::*)(double)> operator[] (uint i) = 0;
};

我希望一个可能的实现看起来像这样:

class g : gBase
{
public:
    g() : g_funcs({{g_00, g_01}}) {}
    vector<cdouble (g::*)(double)>  operator[] (uint i)
    {
        return g_funcs[i];
    }
private:
    vector<vector<cdouble (g::*)(double)> > g_funcs;

    // define each function.
    cdouble g_00(double k)
    {
        return 5.0;
    }

    cdouble g_01(double k)
    {
        return 3.0;
    }
};

我在定义 g_funcs 时哪里出错了?我遇到了这个:

return type is not identical to nor covariant with return type "std::__1::vector<cdouble (gBase::*)(double), std::__1::allocator<cdouble (gBase::*)(double)>>" of overridden virtual function "gBase::operator[]"

最佳答案

A std::vector<T>std::vector<U>即使 T 也不是协变的和 U是协变的。对于模板类型,每个特化都是它自己唯一的类型,除了模板名称之外与其他类型无关。

你需要的是一个普通类型的 vector ,你可以使用 std::function 得到它。 .如果两个函数都返回 std::vector<std::function<double(double)>>那么派生函数将覆盖基础函数。然后,您可以使用捕获 this 的 lambda 来填充 vector 中的函数。因此它具有调用成员函数的对象。

如果您不能这样做,另一种选择是使用 std::vector<std::function<double(gbase const*, double)>>然后您需要将指针传递给您要对其调用函数的对象以及参数。

关于c++ - 在 C++ 中使用成员函数 vector 时,有没有办法实现协变返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54423953/

相关文章:

c++ - Windows服务Win10中的Toast通知

c++ - 如何在一个 while 循环中获取多个条件?

c++ - 无法设置静态对象字段的值(错误 LNK2001 : unresolved external symbol)

c++ - 添加派生类导致ghost错误

php - Doctrine 2 继承映射 : can NULL be used as a discriminator?

c++ - 为什么存储指向内部存储器的普通指针的结构不能存储在 stxxl 容器中?

c++ - 如何将正则表达式 vector 与一个字符串匹配?

c++ - 从对这些项目的引用 vector 访问链接列表项目

c++ - 如何使变量可用于我的函数?

php - 从父级调用覆盖的静态方法