Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++17 Default template arguments: invalid use of template-name without an argument list

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;

like image 958
dcon Avatar asked Jan 14 '20 18:01

dcon


Video Answer


1 Answers

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.

like image 162
JVApen Avatar answered Sep 24 '22 11:09

JVApen