为什么mem func的默认模板参数被明确定义为非法?

时间:2010-12-06 12:55:21

标签: c++ templates c++11

N3126警告:非常大的PDF )14.1 / 9中,有两个语句让我感到困惑:

#1: “可以在模板声明中指定默认模板参数。”

#2: “不应在成员类之外出现的类模板成员定义的template-parameter-lists中指定默认模板参数。”

#1表示以下代码是合法的:

template <class T = int>
void f(T = T())
{}

int main()
{
    int n = f(); // equivalent to f<int>() or f(0);
    return 0;
}

#2表示以下代码是非法的:

template <class T>
struct X
{
    template <class U = T>
    void f(U a = U())
    {}
};

int main()
{
    X<int> x;
    x.f(); // illegal, though I think it should be equivalent to x.f<int>() or x.f(0)
    return 0;
}

我只是想知道为什么后者应该被标准明确定义为非法?

理由是什么?

1 个答案:

答案 0 :(得分:4)

我可能错了,但我对#2的理解是,它使以下非法:

template<class T>
struct A
{
    void foo();
};

template<class T = int>
void A<T>::foo() { /* ... */ }