如何解决模仿“super”关键字:在实例化期间设置“基类”和“派生”类字段
考虑以下代码:
#include <iostream>
struct Parent {
int baseA_ = 0;
double baseB_ = 0.0;
Parent() = default;
virtual ~Parent() = default;
Parent(int a) : baseA_{a} {}
Parent(int a,double b) : baseA_{a},baseB_{b} {}
auto set(int a) -> void { baseA_ = a; }
auto set(int a,double b) -> void {
baseA_ = a;
baseB_ = b;
}
};
struct AnotherParent {
std::string baseA_ = {};
AnotherParent() = default;
virtual ~AnotherParent() = default;
AnotherParent(const std::string &a) : baseA_{a} {}
auto set(const std::string &a) -> void { baseA_ = a; }
};
// Notice that the `Child` class inherits from T.
template <typename T>
struct Child : public T {
int derivedA_ = 0;
Child() = default;
~Child() = default;
Child(int a) : derivedA_{a} {}
auto super(auto... args) -> Child & {
T::set(args...);
return (*this);
}
};
int main() {
auto c1 = Child<Parent>(23).super(23,3.5);
auto c2 = Child<AnotherParent>(243).super("Hello,World!");
std::cout << "C1 - Base -> A: " << c1.baseA_ << ",B: " << c1.baseB_
<< std::endl;
std::cout << "C1 - Derived -> A: " << c1.derivedA_ << std::endl;
std::cout << "C2 - Base -> A: " << c2.baseA_ << std::endl;
std::cout << "C2 - Derived -> A: " << c2.derivedA_ << std::endl;
return 0;
}
编译使用:
g++ -std=c++17 -fconcepts Main.cpp
或
g++ -std=c++14 -fconcepts Main.cpp
我想达到什么目的?
我想在实例化过程中初始化子类(从模板类类型继承)和父类字段。我不想将父类对象作为参数传递给构造函数。
优点:
- 它可用于为任何类型设置
super class
(我的意思是它)数据字段。 - 如果
compiler-error
方法不合适,它会通过生成set()
来提供安全性。 - 无需重载子类构造函数来设置
super class
数据字段 (事实上,没有人可以重载子类构造函数来匹配任何超类,或者这可能吗?我不确定)。 - 调用
super()
是可选的。
限制:
- 仅适用于单继承,但可以实现接口。
- 父类应该有一个
set()
方法。
查询:
- 我实施
super
的方式 - 是一种好的做法吗? - 有什么隐藏的缺点吗?
- 它是否违反了任何习惯用法?
- 可以使用
-fconcepts
吗? - 如果是好的,可以改进吗?比如,我应该实现一些接口以使其更易于维护还是确保
set()
方法的可用性。 - 你有什么看法?
解决方法
您可以将 super
方法替换为转发到基类的模板构造函数。
template <typename T>
struct Child : public T {
int derivedA_ = 0;
Child() = default;
~Child() = default;
Child(int a) : derivedA_{a} {}
template <typename... Args>
Child(int a,Args&&... args) : T{std::forward<Args>(args)...},derivedA_{a} {}
};
现在你可以像这样使用它
auto c1 = Child<Parent>(23,23,3.5);
auto c2 = Child<AnotherParent>(243,"Hello,World!");
auto c3 = Child<Parent>(23,42);
编辑:
只是关于 AnotherParent
的构造函数的注释。由于您通过 const ref 传入 std::string
,因此您始终必须将其复制到成员中。
在这种情况下,最好按值获取参数。在最坏的情况下,您仍然会在那里创建一个副本,但是当我们将右值传递给构造函数时,我们得到的是移动而不是副本。
AnotherParent(std::string a) : baseA_{std::move(a)} {}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。