需要有关初始化期间动态绑定习惯用法的帮助
Need help on the Dynamic Binding During Initialization idiom
我有以下代码:
class A {
public:
A();
virtual int Compute() = 0;
int inited_val;
};
class B: A {
public:
B(int data): mydata(data) {};
int Compute();
int mydata;
};
A::A() {
inited_val = Compute();
};
int B::Compute() {
return mydata; // long computation...
}
int main() {
B b(42);
return 0;
}
这将不起作用,因为在基类的构造函数中CCD_ 1是不可能的(它将调用不存在的CCD_。
如何确保从派生类中的Compute
函数填充inited_val
?我可以从B
构造一个对象,然后填充它,或者使用在构造函数之后直接调用的init函数,但这似乎很容易出错(我可能会忘记这样做)。(假设Compute
函数代价高昂,并且只使用派生类中可用的数据。)
我在上找到了解决这个问题的建议http://isocpp.org/wiki/faq/strange-inheritance#calling-来自ctor习语的virtuals,并试图用create
函数实现该方法,但我不清楚如何在不显式依赖B
的情况下编写A::create
?
A* A::Create() {
A* p = ???;
inited_val = p->Compute();
return p;
}
考虑使用CRTP:
template<class T> class Wrapper : public T
{
public:
template<class... Types>
Wrapper(Types&&... Args)
: T(std::forward<Types>(Args)...)
{
inited_val = Compute();
}
};
int main()
{
Wrapper<B> b(42);
return 0;
}
您可以像这个一样实现B::Compute
0
template <class T>
static std::unique_ptr<typename std::enable_if<std::is_base_of<A, T>::value, T>::type> Create()
{
auto t = std::make_unique<T>();
inited_val = t->Compute();
return t;
}
你可以像这个一样使用它
auto b = Create<B>();
相关文章:
- 视觉studo 2019中的漫画和静态/动态绑定
- 如何理解此C++代码中的动态绑定?
- 移动具有动态绑定的类的分配运算符
- 试图了解动态绑定和虚拟功能
- 为什么动态绑定没有按预期运行?
- 运行时动态绑定和类继承之间的区别
- 是否可以动态绑定运算符>?
- 虚拟函数C++中的动态绑定
- 需要有关初始化期间动态绑定习惯用法的帮助
- 复制对象上的C++动态绑定
- 对象实现后动态绑定大多数不相关的对象
- 套接字动态绑定到缩小范围
- C++ @ 中的动态绑定
- vtable(动态绑定)的C++思想中的多态性
- 动态绑定的条件到底是什么
- 是否有一个模板可以生成类的静态/动态绑定版本
- C++ 静态和动态绑定行为
- 我应该怎么做才能看到静态和动态绑定的作用?[C++]
- 当基类指针指向基类对象时,编译器是否将使用动态绑定
- 对C++中的异常机制执行动态绑定规则