【发布时间】:2012-08-12 20:44:34
【问题描述】:
我正在尝试使用模板化函数中的特征调用显式构造函数/析构函数。
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'
我怀疑缺少一些括号或关键字。
更新
人们问我为什么要这样做......是的,正如预期的那样,我想使用内存池,并为客户端提供两个功能。在内部,它使用一个静态指针指向 malloc/free 的内存池。
template<class Traits>
typename Traits::type_t* memory_pool_new();
template<class Traits>
void memory_pool_delete();
当然,这种方法有局限性……比如只能使用默认构造函数。我想过重载new,但它需要重载所有type_t的new,它会改变现有代码的行为。
【问题讨论】:
-
你为什么要调用析构函数??
-
实际上你想做什么?试图调用哪个析构函数?
标签: c++ typedef destructor traits delete-operator