class模板中成员变量的顺序

the order of member variable in class template

我已经定义了一个 class 模板和一个函数,

template <typename F> class Base {
    public:
        Base(F ff): f(ff) {}
        template <typename... Ps> auto operator() (Ps... ps) const -> decltype(f(ps...)) { return f(ps...); }
    private:
        // f is a pointer to function
        F* f;   
};

int f(int i, int j) 
{
    return i + j;
}

int main()
{
    using f_type = remove_reference<decltype(f)>::type;
    Base<f_type> b{f};
    b(2, 5); // [Error] no match for call to '(Base<int(int, int)>) (int, int)'
}

报告了标记的错误。但是当我改变成员变量的顺序时 class Base,喜欢:

template <typename F> class Base {
    private:
        // f is a pointer to function
        F* f;   
    public:
        Base(F ff): f(ff) {}
        template <typename... Ps> auto operator() (Ps... ps) const -> decltype(f(ps...)) { return f(ps...); }
};

可以编译。

这两个不同结果的原因是什么? 感谢您的宝贵时间!

C++ 中的声明按照它们在源代码中出现的顺序引入。值得注意的例外是成员函数的 bodies:当成员函数在 class 声明中定义时,定义(但不是其声明)的行为就好像函数在 class 定义之后立即定义。

由于关于成员定义位置的规则适用于声明成员函数声明中使用的名称需要在此时声明。更改成员的位置提供了必要的声明。