【问题标题】:differentiating between a function pointer and member function pointer区分函数指针和成员函数指针
【发布时间】:2012-10-03 18:51:55
【问题描述】:

我这个代码,似乎可以工作:

template <typename C>
class class_ {
protected:
    std::map<std::string, native_function> methods;
public:
    template <typename F, F fn>
    class_ &method(const std::string &name) {
        methods[name] = method_helper<C, F>::template toNative<fn>();
        return *this;
    }
};

允许:

class_<MyClass>()
    .method<decltype(&MyClass::numRows), &MyClass::numRows>("numRows");

但是,我还希望允许将非成员函数作为方法添加到导出的类中。问题是我需要一个不同的method 定义来使用正常的函数指针:

template <F, F fn>
class_ &method(const std::string &name) {
    methods[name] = function_helper<F>::template toNative<fn>();
    return *this;
}

但是,如上所示,模板参数将完全相同。

除了创建一个名称完全不同的函数之外,有没有方便的方法来区分函数指针和成员函数指针?或者有没有办法在运行时确定要运行哪些代码?

【问题讨论】:

  • 如果我没记错的话,您正在尝试制作某种脚本绑定系统。你知道cpgf吗?它非常像 luabind(我想你知道),但支持 python、lua 和 javascript。
  • 我是——CPGF 看起来很有趣,谢谢你的链接。我开始编写这段代码的部分原因是我想更好地理解 c++11 标准,但也因为我想要一个轻量级的包装器。

标签: c++ c++11 function-pointers word-wrap member-function-pointers


【解决方案1】:

与SFINAE:

template<
    typename F
    , F fn
    , typename std::enable_if<
        std::is_member_pointer<F>::value
        , int
    >::type...
>
class_ &method(const std::string &name)
{
    methods[name] = method_helper<C, F>::template toNative<fn>();
    return *this;
}

template<
    typename F
    , F fn
    , typename std::enable_if<
        !std::is_member_pointer<F>::value
        , int
    >::type...
>
class_ &method(const std::string &name)
{
    methods[name] = function_helper<F>::template toNative<fn>();
    return *this;
}

【讨论】:

  • 我希望有这样的解决方案!不幸的是,它似乎不适用于当前版本的 clang++。只是为了仔细检查,我尝试使用 g++ 4.6 编译相同的代码,并且编译没有问题。我在使用 clang++ 时遇到的错误是当我尝试调用 method 时,它抱怨 method 不明确。
  • @AbeSchneider 可能是SFINAE technique 的产物。尝试= 0 而不是... 省略号。
【解决方案2】:

您示例中的非成员函数指针将具有签名:

template<typename Ret, typename Args...> Ret (*)(Args args...)

和一个成员函数指针的签名:

template<typename Ret, typename Args...> Ret (C::*)(Args args...)

这使您可以专注于两个签名:

template <typename F, F fn>
class_ &method(const std::string &name) { return method_impl(name, fn); }

template <typename F>
class_ &method_impl(const std::string &name, F fn)
{
    // non-member function variant.
}

template <typename Ret, typename Args...>
class_ &method_impl(const std::string &name, Ret (C::*fn)(Args args...))
{
    // member function variant.
}

注意:如果您将 method_impl 更改为 method,您可以简化您的 API,从而允许:

class_<MyClass>().method("numRows", &MyClass::numRows);

【讨论】:

    猜你喜欢
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    相关资源
    最近更新 更多