我试图在模板化函数中调用具有特征的显式构造函数/析构函数。在模板化函数中调用具有特征的显式构造函数/析构函数
template <int i>
struct Traits
{
};
template <>
struct Traits<1>
{
typedef Foo type_t;
};
template <>
struct Traits<2>
{
typedef Bar type_t;
};
template <class Traits>
void DoSomething(void* p_in)
{
typename Traits::type_t* p = reinterpret_cast<typename Traits::type_t*>(p_in);
// this works.
new (p) typename Traits::type_t;
// neither of following two does work.
p->~typename Traits::type_t();
p->typename ~Traits::type_t();
}
// call
void* p_in = malloc(BIG_ENOUGH);
DoSomething<Traits<1> >(p_in);
free(p_in);
在具有-ansi标志的GCC 4.4.3中,调用显式构造函数可以正常工作。但是,调用显式析构函数不起作用,给出以下错误:
error: expected identifier before 'typename'
error: expected ';' before 'typename'
我怀疑是缺少一些括号或关键字。
UPDATE
人们问我为什么要这么做?是的,正如预期的,我要使用的内存池,并给两个功能给客户。在内部它使用一个静态指针指向内存池malloc/free。
template<class Traits>
typename Traits::type_t* memory_pool_new();
template<class Traits>
void memory_pool_delete();
当然这种方法有局限性...就像只有默认的构造函数可以使用。我想过要重载new,但它需要重载所有type_t的new,它会改变现有代码的行为。
你为什么要调用析构函数? – TemplateRex 2012-08-16 13:32:34
你究竟想做什么?试图调用哪个析构函数? – 2012-08-16 13:34:32