父类有 26 个构造函数重载.如何在不复制+粘贴 26 个重载的情况下将一个小任务附加到所有构造器?



我想从库中派生一个类,以获得多态性的便捷功能。在本例中,父类是来自 OpenCV 4.1 的 cv::Mat

在我的子类中,我们称之为 SpecialMat,我想添加一个简单的属性,无论调用 cv::Mat 的 26 个构造函数中的哪一个,它总是可以在初始化期间计算。我想做的是这样的:

class SpecialMat : public cv::Mat
{
private:
float my_special_property;
void thisFunctionAlwaysCalledAfterConstructor() {
//some constant calculation we can always do at initialization
my_special_property = this.known_property * this.other_known_property;
}
};

有没有办法在不重载 cv::Mat 的所有 26 个构造函数的情况下做这样的事情?有没有办法创建一个构造函数,例如:

SpecialMat(AnyArgs args) : Mat(args), my_special_property(/*calculation goes here*/) {}

哪个会调用任何父类的构造函数?

感谢您的任何建议!

您可以使用可变参数模板。

#include <iostream>
#include <utility>
class Foo {
public:
Foo(int i) {}
Foo(double d, int i) {}
Foo(const Foo& f) {}
Foo(char&& c) {}
};
class Bar : public Foo {
public:
template<typename ...Args>
Bar(Args&&... args) 
:Foo(std::forward<Args>(args)...) {
ExtraFunc();
}
private:
void ExtraFunc() {
std::cout << "Calculating extra valuen";
}
};
void Test() {
int i = 0;
double d = 0;
Foo f{i};
Bar{i};
Bar{d, i};
Bar{f};
Bar('a');
}

戈博尔特

您可以简单地定义一个构造函数,该构造函数将 cv::Mat 作为参数:

class SpecialMat : public cv::Mat
{
public:
SpecialMat(const cv::Mat& mat) :
Mat{ mat }
{
special_func();
}
// Optional, can perform better in some cases. See move semantics if 
// you're not aware of the concept.
SpecialMat(cv::Mat&& mat) :
Mat{ std::move(mat) }
{
special_func();
}
private:
void special_func(void)
{
}
};

这样,类 cv::Mat 可以隐式转换为 SimpleMat :

void f(const SpecialMat& mat)
{
// do some stuff
}
int main(void)
{
cv::Mat m{};
f(m);
SpecialMat m2 = cv::Mat{};
f(m2);
return 0;
}

最新更新