Why is there a need for defaulted-template paramter if the parameter itself is defaulted?

Why is there a need for defaulted-template paramter if the parameter itself is defaulted?

The following code compiles for sleep2() but not for sleep():

#include <iostream>
#include <chrono>

using namespace std;

template<typename Dur>
void sleep( Dur dur = std::chrono::milliseconds::min() )
{
}

template<typename Dur = std::chrono::milliseconds>
void sleep2( Dur dur = Dur::min() )
{
}

int main()
{
    sleep();
    sleep2();
}

This are the MSVC-errors (clang++ and g++ are similar):

'sleep': no matching overloaded function found

Why can't I default a template parameter like with sleep() ?

Answer

In the case of sleep2, the template type parameter Dur has a default value, and so there is no need to specify it when the function is instantiated and invoked. Since the parameter dur also has a default value, you can simply use sleep2(); as you did.

But in the case of sleep there is no such default value for the template parameter.

The compiler will not deduce the type for the template parameter Dur from the default value for dur function parameter.

If you specify it, it will compile:

sleep(std::chrono::milliseconds::min());

Because then the type for Dur can be deduced from the argument.

If you specify the template type explicitly is will also compile (thanks to the default value for dur):

sleep<std::chrono::milliseconds>();

A side note:
sleep is a name of a common function on many systems, so I would change it to e.g. sleep1.

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles