Question

C++

None of these template functions

template<typename T> void foo(T par = nullptr) {return;}  //#1
template<typename T> void foo(T par = std::nullptr_t(nullptr)) {return;}  //#2
template<typename T> void foo(T par = int(0)) {return;}  //#3

allow anything with the following zero-argument call to compile:

foo();

although calling foo with any value works (e.g. foo(2)).

nullptr has a specific type, which is std::nullptr_t, so I didn't think the default parameter needed extra type qualification in #1. The type of the default parameter is explicitly provided in #2 and #3, so I didn't think there was any type ambiguity there.

What is wrong here? Is there a proper way to do default parameters with template functions?

Was it helpful?

Solution

Your examples don't work because template argument deduction fails for foo(). With C++11 you're allowed to specify default template arguments for function templates, so you change the definition to

template<typename T = void*> void foo(T par = nullptr) {return;}

With C++03 I don't know of any way other than to explicitly specify the template argument.

The reason the template argument is not deduced from the default argument is because the standard states that is a non-deduced context.

From N3691, §14.8.2.5/5

The non-deduced contexts are:

...

— A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top