With C++17, you can do class template argument deduction in main like in the following example:
template<class T = int>
struct X{};
int main()
{
X myX;
}
Why is template argument deduction not allowed for data members?
template<class T = int>
struct X{};
struct Y
{
X myX;
};
int main()
{
Y myY;
}
error: invalid use of template-name ‘X’ without an argument list X myX;
I wasn't involved into the decision, however, I do see some problems in allowing it. Let's assume the following code:
template<class T = int>
struct X
{
X(T t = T{}) {}
};
This makes your variable still OK:
int main()
{
Y myY;
}
However, what if Y has a constructor that's implemented in a separate file?
struct Y
{
Y();
X myX{'a'};
};
Y::Y() : myX{0.0} {}
Do we in this case expect myX
to be X<int>
or X<double>
or X<char>
?
I can see that there can be confusion about this. As the standards commite can't revert it's decisions, it's better to take a small step that's certain and see if people need it and what they expect to happen.
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