这行代码是什么意思?它是关于C++的。

3

我在一个名为Selene的项目中看到了这个(一个C++11 Lua封装器),我想知道它是做什么用的?

using Fun = std::function<void()>;
using PFun = std::function<void(Fun)>;

它是一个类(选择器)的私有成员。

相关代码:

namespace sel {
class State;
class Selector {
private:
    friend class State;
    State &_state;
    using Fun = std::function<void()>;
    using PFun = std::function<void(Fun)>;

    // Traverses the structure up to this element
    Fun _traverse;
    // Pushes this element to the stack
    Fun _get;
    // Sets this element from a function that pushes a value to the
    // stack.
    PFun _put;

    // Functor is stored when the () operator is invoked. The argument
    // is used to indicate how many return values are expected
    using Functor = std::function<void(int)>;
    mutable std::unique_ptr<Functor> _functor;

    Selector(State &s, Fun traverse, Fun get, PFun put)
        : _state(s), _traverse(traverse),
          _get(get), _put(put), _functor{nullptr} {}

    Selector(State &s, const char *name);
1个回答

7

这是一个涵盖了typedef功能(以及更多)的C++11语法。

在这种情况下,它创建了一个名为Fun的别名,该别名与std::function<void()>类型相同:

using Fun = std::function<void()>; // same as typedef std::function<void()> Fun

这意味着您可以做到这一点:
void foo() 
{
  std::cout << "foo\n";
}

Fun f = foo; // instead of std::function<void()> f = foo;
f();

同样适用于PFun

嗯,我不知道你可以在类内部使用“using”关键字,就像typedef一样。我以为“using”关键字只用于命名空间。谢谢你的回答。 - SLC
2
@SanduLiviuCatalin 这是关于C++11的内容,也用于别名模板。我已经添加了一条注释和链接。 - juanchopanza
@SanduLiviuCatalin 它使类型定义从左到右与变量定义相同,因此开始使用它是一个好习惯(打趣)。 - TemplateRex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接