gpt4 book ai didi

c++ - 将 new 与 decltype 一起使用

转载 作者:IT老高 更新时间:2023-10-28 22:21:03 26 4
gpt4 key购买 nike

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 ?

最佳答案

如果它们在同一行,您可以使用 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");
}

关于c++ - 将 new 与 decltype 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25309356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com