上下文:我写了一些用于归档数据的工具,类似于来自boost的归档。然后,作为示例,我可以编写这种代码:
class A
{
private:
double a;
public:
A() : a(3.14159)
{}
A(const A& a_) : a(a_.a) {}
virtual ~A()
{}
virtual A* clone() const = 0; // Then, A is virtual
virtual void save(O_Archive& oa) const //
{ //
oa << this->a; // INTERESTING
} // PART OF THE
virtual void load(I_archive& ia) // CLASS
{ //
ia >> this->a; //
} //
};
O_Archive& operator << (O_Archive& oa, const A& a)
{
a.save(oa);
return oa;
}
I_Archive& operator >> (I_Archive& ia, A& a)
{
a.load(ia);
return ia;
}
class B : public A
{
private:
double b;
public:
B() : A(), b(1.0) {}
B(const B& b_) : A(b_), b(b_.b) {}
virtual ~B() {}
virtual A* clone() const
{
return new B(*this);
}
void save(O_Archive& oa) const //
{ //
this->A::save(oa); //
oa << this->b; // INTERESTING
} // PART OF THE
void load(I_Archive& ia) // CLASS
{ //
this->A::load(ia); //
ia >> this->b; //
} //
};
// Consider classes 'C' and 'D' similar to 'B'
void example_save(O_Archive& oa)
{
A* p1 = new B;
A* p2 = new C;
D* p3 = new D;
oa << Archive::declare_derived<A,B,C,D>();
oa << p1 << p2; // Automatically detect the inheritance
oa << p3; // Store the instance as a usual pointer
}
void example_load(I_Archive& ia)
{
A* p1 = 0;
A* p2 = 0;
B* p3 = 0;
ia << Archive::declare_derived<A,B,C,D>();
ia >> p1 >> p2;
ia >> p3;
}
问题出在哪里?这适用于多个函数,例如类load_pointer
中的I_Archive
函数负责检查指针是否已分配,如果是具有派生类型的实例,或者只是通常的指针。
template <typename T>
void I_Archive::load_pointer(T*& p)
{
delete p;
bool allocated;
this->load_bool(allocated);
if(allocated)
{
bool inheriance;
this->load_bool(inheriance);
if(inheriance)
{
unsigned long int i;
this->load_unsigned_long_int(i);
p = boost::static_pointer_cast< const Archive::allocator<T> >(this->alloc[&typeid(T)][i])->allocate();
}
else
p = new T; // ERROR AT THIS LINE
*this >> *p;
}
else
p = 0;
}
我的问题:实际上,我的代码在p = new T;
行上没有编译并出现以下错误:
错误:无法分配抽象类型“A”的对象。
我第一次感到惊讶,但我非常理解为什么会出现此错误:当load_pointer
上调用函数p1
时,指令new T
变为new A
被禁止,即使该类型是抽象的,也不会运行该指令。
我的问题:我无法找到正确使用模板的方法来避免我的错误。是否有可能的解决方法来执行此操作或对编译器&#34;我知道我正在做什么,您将永远不必实例化抽象类型&#34; ?
重要说明:出于兼容性原因,我无法使用C ++ 11。
答案 0 :(得分:2)
您正在寻找的特征是std::is_abstract
。正如您所提到的,您不能使用C ++ 11,但您可以使用来自boost的implementation。
然后,您可以将is_abstract
与std::enable_if
一起使用(再次,由于您不使用C ++ 11的限制,您可以从here获取示例实现)来实现它与此类似:
#include <iostream>
#include <type_traits>
struct A {
virtual void f() = 0;
};
struct B : A {
void f() override {}
};
template<typename T>
std::enable_if_t<std::is_abstract<T>::value, T*> allocate()
{
return nullptr;
}
template<typename T>
std::enable_if_t<!std::is_abstract<T>::value, T*> allocate()
{
return new T;
}
// Test
template<typename T>
T* test_alloc()
{
return allocate<T>();
}
int main()
{
std::cout << test_alloc<A>() << "\n"; // Outputs nullptr
std::cout << test_alloc<B>() << "\n"; // Outputs an address
}