为什么下面没有编译错误?:
// 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
}
看起来好像 13 被编译器默默地忽略了。 这是为什么?
奇怪的是,如果类模板定义位于 Main.cpp 而不是头文件中,我确实会收到 默认参数重新定义 错误。
现在我知道如果它只是一个普通(非模板)函数,编译器会抱怨这一点。
标准对类模板成员函数或函数模板中的默认参数有什么规定?
8.3.6 §6 成员函数定义中的默认参数 出现在课堂之外 定义被添加到集合中 提供的默认参数 中的成员函数声明 类定义。
[示例: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
--示例结束]
根据标准,它应该给你一个错误。