C ++能以某种方式接受'auto'的使用吗?
class A { public: A(): m_member(new auto) { [...] } private: BoringToTypeType *m_member; }目的是通过简化A构造函数中的成员元素初始化来利用'auto'。 事实上,代码引发了以下错误:
new expression for type 'auto' requires a constructor argument.Can C++ somehow accept this use of 'auto'?:
class A { public: A(): m_member(new auto) { [...] } private: BoringToTypeType *m_member; }The purpose is to take advantage of 'auto' by simplifying the member element initialisation in A's constructor. As it is, the code raises the following error:
new expression for type 'auto' requires a constructor argument.最满意答案
new auto(...)从内部传递的表达式new auto(...)推导出结果指针的类型。 在你的特定情况下,没有什么可以推断的。
你有几个选择:
m_member(new auto(x)) ,其中x是BoringToTypeType类型的BoringToTypeType 。
m_member(new std::remove_pointer_t<decltype(m_member)>) ,这肯定不是BoringToTypeType的改进。
如果你不介意定义一个辅助函数,这里有一个替代解决方案:
template <typename T, typename... TArgs> auto newer(T*, TArgs&&... args) { return new T(std::forward<TArgs>(args)...); } class A { public: A(): m_member(newer(m_member, 12)) { } private: int *m_member; };在这种情况下, T纯粹用于类型演绎目的。 m_member必须重复两次,但是你不要这样输入它的类型。
在godbolt.org上进行的简单测试表明, newer不会产生额外的开销。
new auto(...) deduces the type of the resultant pointer from the expression passed inside (...). In your particular case there's nothing that can be deduced.
You have a few options:
m_member(new auto(x)), where x is an expression of type BoringToTypeType.
m_member(new std::remove_pointer_t<decltype(m_member)>), which is most certainly not an improvement over BoringToTypeType.
If you don't mind defining an additional helper function, here's an alternative solution:
template <typename T, typename... TArgs> auto newer(T*, TArgs&&... args) { return new T(std::forward<TArgs>(args)...); } class A { public: A(): m_member(newer(m_member, 12)) { } private: int *m_member; };In this case T is used purely for type deduction purposes. m_member has to be repeated twice, but you avoid typing out its type this way.
Simple tests on godbolt.org show that newer does not incur any additional overhead.
更多推荐
发布评论