在C++中,成员函数指针的const
属性如何确定?以下代码是否有效?
struct T {
void foo(int i) const { std::cout << i << std::endl;};
};
void (T::*f1)(int) const = &T::foo;
void (T::*f2)(int) = reinterpret_cast<void (T::*)(int)>(f1);
T t;
(t.*f2)(1);
更新:
我需要这个的原因是,我正在编写一个函数,它既接受对象,也接受指向该对象的成员函数指针。我需要一个版本来处理const对象(只接受const函数),还需要一个普通版本。由于我不想重复编写代码,我的想法是将实际代码放在非const版本中,并从const版本中调用它,消除任何const。