简体   繁体   中英

How to remove const qualifier from a member function pointer

I'm using a library which contains the following code:

template <typename M>
void _register_member(lua_State *state,
                      const char *member_name,
                      M T::*member) {
    std::function<M(T*)> lambda_get = [member](T *t) {
                //^ error here
        return t->*member;
    };
    //...

However this code does not accept const member function pointers. Passing those yields the error Function cannot return function type 'void () const' or whatever the type of the const member function is.

How do I remove the const qualifier from the passed member function or how do I apply std::remove_const ?

As Adam S noted in comments this error occurs when he tries to compile this simple code which uses the library Selene :

#include <selene.h>

class C {
public:
    bool get() const;
};

bool C::get() const {return true;}

int main() {
    sel::State state;
    state["C"].SetClass<C>("get", &C::get);
}

The compiler fails to compile the code in Class.h header. There are two overloads of function member _register_member of the class Class in it:

template <typename T,
          typename A,
          typename... Members>
class Class : public BaseClass {
private:

    // ...

    template <typename M>
    void _register_member(lua_State *state,
                          const char *member_name,
                          M T::*member) {
        // ...
    }

    template <typename Ret, typename... Args>
    void _register_member(lua_State *state,
                          const char *fun_name,
                          Ret(T::*fun)(Args...)) {
        // ...
    }

    // ...

};

The compiler can't choose the second overload when a pointer to a const function member is passed as a third argument. There should be another overload which could accept a const function member. It should be declared as follows:

template <typename Ret, typename... Args>
void _register_member(lua_State *state,
                      const char *fun_name,
                      Ret(T::*fun)(Args...) const)
                                            ^^^^^

Without such overload the compiler chooses the first overload which is created to work with pointers to data members (not function members) and fails to compile its code.

So you can't deal with const function members when using current version of Selena library (in such way as you do it at least).

我应该提一下,对于那些现在看到这个,这实际上是我的代码中的一个错误(真的是疏忽)并且在问题被识别后不久就修复了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM