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.
看起来好像13只是被编译器悄悄地忽略了。这是为什么呢?如果类模板定义是主类,那么问题就来了。cpp而不是头文件,我确实得到了默认参数重新定义错误。
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?
在类模板成员函数或函数模板中,标准对默认参数有什么要求?
1 个解决方案
#1
3
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:求§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
--end example]
——最后的例子)
According to the standard, it should give you an error.
根据标准,它会给你一个错误。
#1
3
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:求§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
--end example]
——最后的例子)
According to the standard, it should give you an error.
根据标准,它会给你一个错误。