在方法重载的情况下如何获取const方法指针?

时间:2019-04-09 18:21:08

标签: c++

class C {
public:
    int x() const { return x_; }
    int& x() { return x_; }
private:
    int x_{0};
};

std::function<int(C const&)> f{static_cast<int (C::*)() const>(&C::x)}; // compiles
std::function<int(C const&)> f{&C::x}; // does not compile, as it takes pointer of non-const method

在这种情况下,有没有办法避免这种丑陋的转换并获取const方法指针?

我经历了How do I specify a pointer to an overloaded function?,它解释了为什么在这里不幸必须强制使用cast(或指向const方法类型的指针的中间变量)。
在我的问题中,我有这样的指针数组,并在单独的函数中处理它们。最后,我只保留了数组而不进行任何强制转换(因此采用了指向非const方法的指针),并且只是在处理函数内部删除了constness(使用const_cast)以避免编译错误。对这种解决方案不满意,但是我认为这比为每个方法指针放置“丑陋”的转换更好。

0 个答案:

没有答案