本文介绍了使用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
回答为什么 decltype(* t)
返回 T&
,而不是 T
。
This answers why decltype(*t)
returns T &
and not T
.
我可以把我的最后一行放入一个宏,但似乎不太理想。
有没有比我迄今为止更好的解决方案?这是否属于?
I can put my last line into a macro, but that seems suboptimal.Is there a better solution than what I have so far? Does this belong on Code Review?
推荐答案
如果他们在同一行,您可以使用 auto
只输入 T
一次:
If they're on the same line, you can use auto
to only name T
once:
auto t = new T;
否则,您可以创建一个小函数模板:
Otherwise, you could create a small function template:
template <class T>
void do_new(T * &p) {
p = new T;
}
// Usage:
int main()
{
T *t;
do_new(t);
}
正如@MadScienceDreams指出的,您可以将其扩展为允许非默认构造函数:
As @MadScienceDreams pointed out, you can extend this to allow non-default constructors:
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");
}
这篇关于使用decltype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!