I couldn't find any information on Google about this, In the following example:
#include <iostream>
class Default
{
public:
void Print()
{
std::cout << "This is a message\n";
}
};
template <class C = Default>
class Template
{
public:
static void Test()
{
Default oDefault();
}
};
int main()
{
return 0;
}
the code fails to compile with the error:
In static member function ‘static void Template::Test()’: 19:22: error: default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x
The trouble is that it doesn't like the brackets appearing on that line and I don't understand why. If I remove the brackets the code compiles just fine. Also if I remove the template declaration (line 13) it also compiles just fine. Is this a bug or is there some rule somewhere about exactly this situation?
I'm using g++4.6.1 (gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3))
Change it to:
Default oDefault = Default(); // Version 1
Though you can use:
Default oDefault; // Version 2
This has a slightly different meaning.
Through version one looks like it invokes an extra copy construction this is not the case (in most compilers) as the extra copy will be elided by the compiler and a simple normal (zero-initialized) construction will happen.
You should prefer zero-initialization to default (in general) as if the class (or any members type) does not have a user defined constructor (Like Default) then the difference is that default-initialization leaves POD members undefined while zero-initialized leaves POD members initialized to zero. Now you may think now that my class has no members so it does not matter. But what happens if you modify the class are you going to go and find all instances and update them; Best to use version one and let the compiler do the correct thing.
For all the mind blowing details see:
The reason your initial version did not work is that it is actually a forward declaration of a function. This is caused by the complex syntax of C++ and just one of the rules you need to remember. You can look this up as "The Most Vexing Parse".