我的基类看起来像(当然有构造函数):
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/