c++ - 类模板成员函数没有 "redefinition of default parameter error"?

标签 c++ visual-c++ templates compiler-construction

为什么下面没有编译错误?:

// 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/

相关文章:

c++ - 关于C++17中类模板参数推导的问题

c++ - 指向数组的指针的 Malloc - C++

c++ - 使用/clr 选项编译 C 代码

templates - 混合模板 : how to halt compilation?

visual-studio-2010 - 无法在 VSIX 部署模板中引用向导程序集

templates - 如何从 Polymer 模板中访问自定义元素的主体?

c++ - 我们可以使用 std::vector 定义一个固定宽度的二维矩阵吗?

C++ Visual Studio 2010 不链接 native 静态库

c++ - Rvalue 成员确实也是 Rvalues 吗?

C++:指针 vector 在 push_back() 之后失去引用