这是一个模板函数,它接受一个指针(或类似指针的对象)和一个成员函数:
template <typename Ptr, typename MemberFunctor>
int example(Ptr ptr, MemberFunctor func )
{
return (ptr->*func)();
}
Run Code Online (Sandbox Code Playgroud)
如果与普通指针一起使用时有效:
struct C
{
int getId() const { return 1; }
};
C* c = new C;
example(c, &C::getId); // Works fine
Run Code Online (Sandbox Code Playgroud)
但它不适用于智能指针:
std::shared_ptr<C> c2(new C);
example(c2, &C::getId);
Run Code Online (Sandbox Code Playgroud)
错误信息:
error: C2296: '->*' : illegal, left operand has type 'std::shared_ptr<C>'
Run Code Online (Sandbox Code Playgroud)
为什么?以及如何制作适合两者的东西?
最近我发现shared_ptr没有指向成员运算符的指针->*.我创建了简单的例子:
template <typename Pointer, typename Function, typename... Args>
auto invoke1(Pointer p, Function f, Args... args) -> decltype((p->*f)(args...))
{
return (p->*f)(args...);
}
struct A {
void g() { std::cout << "A::g()\n"; }
};
int main() {
A a;
invoke1(&a, &A::g); // works!!
std::shared_ptr<A> sa = std::make_shared<A>();
invoke1(sa, &A::g); // compile error!!
}
Run Code Online (Sandbox Code Playgroud)
Q1:为什么会这样?为什么shared_ptr没有这个运算符?
我添加了这样的运算符,shared_ptr示例开始工作:
template <typename T, typename Result>
auto operator ->* (std::shared_ptr<T> pointer, Result (T::*function)()) ->decltype(std::bind(function, pointer))
{
return std::bind(function, pointer);
}
template <typename …Run Code Online (Sandbox Code Playgroud) c++ operator-overloading boost-bind shared-ptr pointer-to-member
我有一个课程如下
class A
{
public:
A(int key) : m_key(key) {}
int Key() const {return m_key;}
private:
int m_key;
};
Run Code Online (Sandbox Code Playgroud)
我使用带有成员函数指针的unique_ptr进行测试
int (A::*MemFun)() const;
MemFun = &A::Key;
( std::unique_ptr<A>(new A(10)) ->*MemFun ) (); // Error C2296
( std::unique_ptr<A>(new A(10)).get() ->*MemFun ) (); // okay
(*std::unique_ptr<A>(new A(10)) .*MemFun ) (); // okay
Run Code Online (Sandbox Code Playgroud)
第一个给出编译错误(VC2010给出错误C2296,非法,左运算符包括std :: unique_ptr <_Ty>).为什么?谢谢.