Reputation: 993
I have problem with my template class. I specified default type of my template class like that:
template < class T = float >
class apple {
public:
T x;
apple(T x): x(x) {}
}
However, when I create the object like that:
apple obj(2);
The type turns into int unless I do that:
apple<float> obj(2);
How would I make it stay float?
Upvotes: 4
Views: 213
Reputation: 96071
Another possible solution is to modify the constructor:
apple(std::enable_if_t<1, T> x): x(x) {}
This way the compiler won't be able to deduce T
from an argument you pass to x
, and will use the default type for T
(that you provided) instead.
Upvotes: 1
Reputation: 63124
Add this deduction guide to force all argument deductions to resolve to your default arguments:
template <class T>
apple(T) -> apple<>;
Upvotes: 5
Reputation: 310950
Use the specialization for the default template parameter like
apple<> obj( 2 );
Upvotes: 3