使用new与decltype

时间:2014-08-14 13:33:59

标签: c++ c++11 decltype

T *t; //T is an implementation detail
t = new T; //want to avoid naming T to allow for flexibility
t = new decltype(*t); //error: cannot use 'new' to allocate a reference
t = new std::remove_reference<decltype(*t)>::type(); //clunky

This回答了decltype(*t)返回T &而不是T的原因。

我可以将我的最后一行放入宏中,但这似乎不是最理想的。 有没有比我到目前为止更好的解决方案?这属于Code Review吗?

2 个答案:

答案 0 :(得分:11)

如果他们在同一行,您可以使用auto仅命名T一次:

auto t = new T;

否则,您可以创建一个小功能模板:

template <class T>
void do_new(T * &p) {
  p = new T;
}


// Usage:
int main()
{
  T *t;
  do_new(t);
}

正如@MadScienceDreams指出的那样,你可以扩展它以允许非默认的构造函数:

template <class T, class... Arg>
void do_new(T * &p, Arg &&... arg) {
  p = new T(std::forward<Arg>(arg)...);
}


// Usage:
int main()
{
  T *t;
  do_new(t);
  std::string *s;
  do_new(s, "Abc");
}

答案 1 :(得分:4)

std::remove_pointer<decltype(t)>::type更具表现力/清晰度。

如果重复多次,您也可以使用本地typedef,或者使某条线长得太长/太复杂。