我有各种从模板类栏(下)创建的对象。每个对象都有一个具有不同数据类型的数据成员(例如 std::string、bool、int 等)
我在一个静态数组中有一组当前默认值,每个派生/模板化类型都是通过 new 构造的。
我想在构造函数中初始化对象,而不需要单独的初始化步骤。
我可以确定我从静态数组中检索的默认对象的类型绝对是 SAME 模板化类型。
我想我遇到的问题是,在构造函数完成之前,对象栏并不是真正的对象栏类型?在 C++11 中没有办法使用目标或委托构造函数来解决这个问题吗?
class foo
{
public:
foo(int index) : fMyIndex(index) { }
protected:
int fMyIndex;
};
template<class T>
class bar : public foo
{
public:
// This constructor takes the integer prefIndex, then constructs
// the object based on current in-memory settings, which it obtains from a static array via static GetDefaultData;
//
bar(int index) : foo(index)
{
// get the most current version of the in-memory data. defaultObject is a pointer to a "BarString"
foo* defaultObject = static_cast<bar*>(GetDefaultData(fMyIndex));
if (defaultObject) {
// bad memory access!
*this = *defaultObject;
}
}
private:
T fMyData;
};
typedef bar<std::string> BarString;
typedef bar<int> BarInt;
typedef bar<bool> BarBool;