对基构造函数的条件调用
Conditional call to base constructor
目前,我有一个具有两个不同构造函数的基础类:
class Base {
public:
Base(std::string filname){...}
Base(int a, int b) {...}
};
以及基类的派生类。我想做的是在派生类的构造函数中选择哪个构造函数调用,而不是在初始值设定项列表中。像这样:
class Derived : public Base {
public:
Derived() {
if( /* exists("myFile") */ )
this->Base("myFile");
else
this->Base(1,2);
}
}
是否可以这样做?,或者因为基类在派生类之前初始化,所以调用基构造函数的唯一方法是在初始值设定项列表中?
谢谢
选择调用哪个基构造函数发生在函数主体之前,并且无法像这样在运行时更改它。但是,您也许可以接近。如果基类也有一个移动构造函数,或者你可以添加一个,你可以使用它:
class Derived : public Base {
public:
Derived()
: Base{ exists("myFile") ? Base{"myFile"} : Base{1, 2} } {
}
}
这将调用exists("myFile")
;如果返回true
,它将使用第一个构造函数构造一个临时Base
,如果它返回false
它将使用第二个构造函数构造一个临时Base
。无论哪种方式,它都将使用此临时子对象构造实际的基本子对象。
您可以通过引入工厂函数来模拟它:
class Base {
public:
Base(std::string filname);
Base(int a, int b);
};
class Derived : public Base {
Derived(std::string filname) : Base(filname) {}
Derived(int a, int b) : Base(a, b) {}
public:
static Derived create() {
if( /* exists("myFile") */ )
return Derived("myFile");
else
return Derived(1,2);
}
};
int main(){
auto d = Derived::create();
}
或者,如果不需要从Base
派生,则可以将Base
的实例视为成员(std::unique_ptr
或std::aligned_storage
(,您可以随意初始化。
基于他回答中的@DanielH评论,我开发了一个替代解决方案,该解决方案也适用于 C++11 中的抽象基类:
#include <iostream>
struct Base {
Base(int x) {
std::cout << "Base x = " << x << std::endl;
}
Base() {
std::cout << "Base default" << std::endl;
}
virtual void foo() = 0;
};
struct Derived : Base {
struct TagA {};
struct TagB {};
Derived(bool condition)
: Derived(condition ? Derived{TagA()} : Derived{TagB()})
{}
void foo() override {}
private:
Derived(TagA dummy)
: Base(42)
{
std::cout << "Derived A dummy" << std::endl;
}
Derived(TagB dummy)
{
std::cout << "Derived B dummy" << std::endl;
}
};
int main() {
std::cout << "Construct Derived with false" << std::endl;
Derived x(false);
std::cout << "Construct Derived with true" << std::endl;
Derived y(true);
}
相关文章:
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 访问条件类成员的方法不仅在被调用时才编译
- 在运行时有条件地删除类成员或跳过调用该成员对象的构造函数
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 条件加倍时的递归调用
- "is defined"宏检查及其调用必须处于不同的条件下吗?
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- 在循环条件中调用const vector size()似乎缺少优化
- 对基构造函数的条件调用
- 在解压缩可变参数模板时避免"recursive"函数调用,直到运行时条件
- 如何避免参数数量依赖于条件的调用分支?
- 使用条件模板C 调用功能
- 现代C++编译器是否能够避免在某些条件下两次调用常量函数
- 构造函数的条件调用
- 使用模板调用条件函数
- 调用以条件循环(c++)
- 在 CPP 中将函数调用定时为 if 语句条件
- 中断已处于条件变量等待调用中的提升线程
- 在条件调用new时调用delete
- 使用条件调用模板函数