Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why c++ allows default template argument that can never be used?

If I have a function template that has default argument for its template parameter and that function takes a non-default parameter of the type parameter then what's the point in the language to allow that default argument that'll never be used? :

template <class T = int>
void foo(T x){cout << x << endl;}

int main()
{

    foo("hi"); // T is char const *
    foo(); // error
}

As you can see T=int can never be used because the function doesn't have a default parameter thus the compiler in this context always deduces the type of T from the argument passed to foo.

like image 216
Maestro Avatar asked Jan 22 '26 05:01

Maestro


1 Answers

But it can be used. Here's an example.

auto* foo_ptr = &foo<>; // The default template argument is used.

A function call expression is not the only context where a function template's arguments need to be figured out.

like image 62
StoryTeller - Unslander Monica Avatar answered Jan 24 '26 23:01

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!