Unexpected behaviour when using function as default argument

The following code works as expected:
 
template <class T> void fn(const T& arg = T()) { ... }

Defaulting the parameter to 0 when an fn<int> is called, for example.

However, I rewrote this code as follows:
1
2
3
template <class T> inline T Default() { return T(); }

template <class T> void fn(const T& arg = Default<T>()) { ... }

so that a particular argument type could have custom defaults if desired. However, when I use this code an integer argument now defaults to something like -8643563, i.e. it appears not to have been properly initialized.

My question, therefore, is what makes the second code sample not work, but the first to work?

Thanks for any help.
Last edited on
EDIT:

Explicitly putting the function as an argument:
 
fn(Default<int>());

works. It is only when the default argument is required:
 
fn();

that the argument is not set to default as expected.
EDIT EDIT: Ah fixed it now. I had implemented the relevant function (which was a template class member) outside the class and for some reason the compiler was ignoring the default arguments in the function prototype inside the class. To fix it I just put the default parameters in the header of the function definition outside the class.
Topic archived. No new replies allowed.