c++ 11: std::mem_fn的类型名

C++11 : type name for std::mem_fn

本文关键字:类型 fn mem std c++      更新时间:2023-10-16

auto很好,但我需要在类中声明成员,而不是堆栈中的变量。

decltype工作,但不知何故看起来很奇怪

class Automation {
    void _init_state(int);
    decltype(std::mem_fn(&Automation::_init_state)) next_state;
};

std::function似乎也可以工作,但与纯成员函数

略有不同
class Automation {
    void _init_state(int) {}
public:
    decltype(std::mem_fn(&Automation::_init_state)) next_state;
    std::function<void(Automation&, int)> next_state_fn;
    Automation()
        : next_state(&Automation::_init_state)
        , next_state_fn(&Automation::_init_state)
    {}
};
int main()
{
    /* on ubuntu, x64 */
    std::cout << sizeof Automation::next_state << std::endl; /* 16 */
    std::cout << sizeof Automation::next_state_fn << std::endl; /* 32 */
    return 0;
}
谁能告诉我正确的方法是什么?

标准未指定std::mem_fn的返回类型,因此没有可移植的方法来显式声明该类型的成员变量。

虽然decltype结构可能看起来很奇怪,但这是正确的方法。std::function会产生一些开销,但是更灵活,因为可以比使用decltype版本更容易地传递它。