【问题标题】:How to pass const member function as non-const member function如何将 const 成员函数作为非常量成员函数传递
【发布时间】:2019-05-04 21:12:30
【问题描述】:

如何将 const 成员函数 作为 non-const 成员函数 传递给模板?

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
}

不想添加类似:

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

有没有更好的办法?

【问题讨论】:

  • 你需要函数来接受函数指针吗?只需采用通用函数类型或 std::function 即可。

标签: c++ class c++11 templates member-function-pointers


【解决方案1】:

为什么不简单地将它传递给通用模板函数:

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
}

输出

non-cost
cost with no args
cost with one arg: 1
cost with args: 1 2.02

【讨论】:

  • 这种方法不适合我的情况。我需要处理参数(从 lua_toxxxx 之类的东西中获取)和返回值(将其推送到 lua_pushxxxx 之类的东西中)。我终于使用函数重载来做到这一点。如此丑陋但工作.. :(
【解决方案2】:

不,您必须指定要匹配的 cv 和 ref 限定符。对于任何给定的RTArgs...R(T::*func)(Args...)R(T::*func)(Args...) const 的独立类型。

作为一个术语说明,它并不模棱两可。只有一个候选人,它不匹配。歧义需要多个匹配的候选者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    相关资源
    最近更新 更多