[英]Is there a way to implement covariant return types when using a vector of member functions in C++?
我的基類看起來像(當然有構造函數):
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[]"
即使T
和U
是協變的, std::vector<T>
和std::vector<U>
也不協變。 對於模板類型,每個專門化都是它自己的唯一類型,除了模板名稱之外,其他類型都沒有關系。
您需要的是通用類型的向量,您可以使用std::function
獲得它。 如果兩個函數都返回一個std::vector<std::function<double(double)>>
則派生函數將覆蓋基函數。 然后,您可以使用捕獲了this
的lambda來填充矢量中的函數,以便它具有對象來調用成員函數。
如果您不能執行此操作,則另一種選擇是使用std::vector<std::function<double(gbase const*, double)>>
,然后需要將指針傳遞給您要調用的對象功能加上參數。
您將必須返回std::vector<cdouble (gBase::*)(double)>
,因為std::vector<cdouble (gBase::*)(double)>
與std::vector<cdouble (g::*)(double)>
之間沒有關系std::vector<cdouble (g::*)(double)>
還要注意, g[i][alpha](k)
不會調用這些函數之一,因為您沒有傳遞將是this
的g
(作為gBase
)。 你可以代替
(g.*g[i][alpha])(k)
或使用C ++ 17
std::invoke(g[i][alpha], g, k);
但它確實聽起來像你要束起來this
與載體的功能。 在這種情況下,您應該
class gBase
{
public:
// The user will implement a vector of a vector of functions that can be called as g[i][alpha](k)
virtual std::vector<std::function<double(double)> > operator[] (uint i) = 0;
};
class g : public gBase
{
public:
g() : g_funcs({{[this](double k){ return g_00(k); }, [this](double k){ return g_01(k); }}}) {}
std::vector<std::function<double(double)> > operator[] (uint i)
{
return g_funcs[i];
}
private:
std::vector<std::vector<std::function<double(double)> > > g_funcs;
// define each function.
cdouble g_00(double k)
{
return 5.0;
}
cdouble g_01(double k)
{
return 3.0;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.