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(...)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With