为什么下面没有编译错误?:
// 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 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]
按照标准,它应该给你一个错误。
关于c++ - 类模板成员函数没有 "redefinition of default parameter error"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2479846/