Appleshell
Appleshell

Reputation: 7388

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?

Upvotes: 9

Views: 2648

Answers (2)

jeremyong
jeremyong

Reputation: 484

I should mention that for those viewing this now, this was in fact a bug in my code (an oversight really) and it was fixed shortly after the problem was identified.

Upvotes: 1

Constructor
Constructor

Reputation: 7493

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).

Upvotes: 1

Related Questions