4

How to pass a const member function as a non-const member function to the template?

class TestA 
{
public:
    void A() {
    }

    void B() const {
    }
};

template<typename T, typename R, typename... Args>
void regFunc(R(T::*func)(Args...)) 
{}

void test() 
{
    regFunc(&TestA::A); // OK
    regFunc(&TestA::B); // ambiguous
}

Don't want to add something like:

void regFunc(R(T::*func)(Args...) const)

Is there a better way?

1
  • 2
    Do you need the function to accept a function pointer? Just taking a generic function type or a std::function should work. Commented Dec 3, 2018 at 14:46

2 Answers 2

5

Why not simply pass it to a generic template function:

see live

#include <iostream>
#include <utility>

class TestA
{
public:
    void A() { std::cout << "non-cost\n"; }
    void B() const { std::cout << "cost with no args\n"; }
    void B2(int a) const { std::cout << "cost with one arg\n"; }
    const void B3(int a, float f) const { std::cout << "cost with args\n"; }
};
template<class Class, typename fType, typename... Args>
void regFunc(fType member_fun, Args&&... args)
{
    Class Obj{};
    (Obj.*member_fun)(std::forward<Args>(args)...);
}

void test()
{
    regFunc<TestA>(&TestA::A); // OK
    regFunc<TestA>(&TestA::B); // OK
    regFunc<TestA>(&TestA::B2, 1); // OK
    regFunc<TestA>(&TestA::B3, 1, 2.02f); // OK
}

output:

non-cost
cost with no args
cost with one arg: 1
cost with args: 1 2.02
Sign up to request clarification or add additional context in comments.

1 Comment

This approach doesn't fit my situation. I need to handle the arguments(get it from something like lua_toxxxx) and the return value ( push it into something like lua_pushxxxx). I finally use function overloading to do this. so ugly but work.. :(
2

No, you have to specify the cv and ref qualifiers to match. R(T::*func)(Args...) is a separate type to R(T::*func)(Args...) const for any given R, T, Args....

As a terminology note, it isn't ambiguous. There is exactly one candidate, it doesn't match. Ambiguity requires multiple matching candidates.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.