在模板化函数中调用带有特征的显式构造函数/析构函数 [英] Call explicit constructor/destructor with traits in templatized function

查看:94
本文介绍了在模板化函数中调用带有特征的显式构造函数/析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在模板化函数中使用带有特征的显式构造函数/析构函数.

I'm trying to call explicit constructor/destructor with traits in templatized function.

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中,调用显式构造函数可以正常工作.但是,调用显式析构函数不起作用,从而产生以下错误:

In GCC 4.4.3 with -ansi flag, calling explicit constructor works fine. However, calling explicit destructor does not work, giving following error:

error: expected identifier before 'typename'
error: expected ';' before 'typename'

我怀疑缺少一些括号或关键字.

I suspect some parentheses or keyword is missing.

更新

人们问我为什么要这样做...是的,正如我期望的那样,我想使用内存池,并为客户端提供两个功能.在内部,它使用指向内存池的静态指针进行malloc/free.

People ask about why I am doing this... Yes, as expected, I want to use memory pool, and give two functions to clients. Internally it uses a static pointer to the memory pool for malloc/free.

template<class Traits>
typename Traits::type_t* memory_pool_new();
template<class Traits>
void memory_pool_delete();

当然,这种方法有局限性...就像只能使用默认构造函数一样.我曾考虑过重载new,但是它需要重载所有type_t中的new,这将改变现有代码的行为.

Of course this approach has limitations... like only default constructor can be used. I thought about overloading new, but it requires overloading new of all type_t's, and it will change the behavior of existing codes.

推荐答案

MSDN网站提供了

The MSDN site gives this example:

要显式调用类的对象 s 的析构函数 String ,请使用以下语句之一:

To explicitly call the destructor for an object, s, of class String, use one of the following statements:

s.String::~String();     // Nonvirtual call
ps->String::~String();   // Nonvirtual call

s.~String();       // Virtual call
ps->~String();     // Virtual call

因此,您可以尝试添加typedef并使用以下内容模仿上面的内容:

So you could try to add a typedef and mimic the above with:

typedef typename Traits::type_t TraitsType;

// we now have that p is of TraitsType*
p->TraitsType::~TraitsType(); // nonvirtual call
p->~TraitsType();             // virtual call

这篇关于在模板化函数中调用带有特征的显式构造函数/析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆