Why does the following give no compilation error?:
// T.h
template<class T> class X
{
public:
void foo(int a = 42);
};
// Main.cpp
#include "T.h"
#include <iostream>
template<class T> void X<T>::foo(int a = 13)
{
std::cout << a << std::endl;
}
int main()
{
X<int> x;
x.foo(); // prints 42
}
It seems as开发者_如何学编程 though the 13 is just silently ignored by the compiler. Why is this?
The cooky thing is that if the class template definition is in Main.cpp instead of a header file, I do indeed get the default parameter redefinition error.Now I know the compiler will complain about this if it were just an ordinary (non-template) function.
What does the standard have to say about default parameters in class template member functions or function templates?
8.3.6 §6 The default arguments in a member function definition that appears outside of the class definition are added to the set of default arguments provided by the member function declaration in the class definition.
[Example:class C { void f(int i = 3); void g(int i, int j = 99); }; void C::f(int i = 3) // error: default argument already { } // specified in class scope void C::g(int i = 88, int j) // in this translation unit, { } // C::g can be called with no argument
--end example]
According to the standard, it should give you an error.
精彩评论