类模板中成员变量的顺序

the order of member variable in class template

本文关键字:变量 顺序 成员      更新时间:2023-10-16

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

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 :当在类声明中定义成员函数时,定义(而不是其声明)的行为,好像该函数在类之后立即定义定义。

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