如何将const成员函数作为非const成员函数传递

时间:2018-12-03 14:43:04

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

如何将 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)

有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

否,您必须指定cv和ref限定词来匹配。对于任何给定的R(T::*func)(Args...)R(T::*func)(Args...) constRTArgs...的独立类型。

作为术语注释,它不是模棱两可。仅有一个候选人,但不匹配。模糊性需要多个匹配的候选对象。

相关问题