类指针类和 - > *运算符 [英] Pointer-like classes and the ->* operator
问题描述
我最近遇到了将指针指向成员应用于迭代器指定的对象的需要。我尝试过自然语法:
I've recently come across the need to apply a pointer-to-member to the object designated by an iterator. I've tried the natural syntax :
ite->*ptr = 42;
令我沮丧的是,它没有编译。迭代器不会超载 operator-> *
,但更令人惊讶的是智能指针也不会。我需要诉诸以下笨拙:
To my dismay, it didn't compile. Iterators don't overload operator->*
, but more surprisingly neither do smart pointers. I needed to resort to the following clunkiness :
(*ite).*ptr = 42;
试验(参见下面的实例)已经证明,自定义类似乎可以实现这样的语法,对于指向成员的指针和指向成员函数的指针,至少从C ++ 14开始。
Experimenting (see the live example below) has shown that such a syntax seems to be achievable for custom classes, for both pointers-to-members and pointers-to-member-functions, at least since C++14.
因此:
- 是否有一个原因,标准指针式类不会超载
operator-> *
,或者是它只是一个疏忽? - 在定义我自己的类指针类时,我应该重载
operator-> *
,或者是否有相同的原因适用于我?
- Is there a reason the standard pointer-like classes don't overload
operator->*
, or is it just an oversight ? - Should I overload
operator->*
when defining my own pointer-like classes, or does this same reason apply to me ?
实例 - 自定义类的编译,不编码和概念验证。
Live example -- what compiles, what doesn't, and a proof-of-concept for a custom class.
推荐答案
您可以使用免费功能重载 - > *
。它不一定是会员。
You can overload ->*
with a free function. It doesn't have to be a member.
template <typename P,
typename T,
typename M>
M& operator->* (P smartptr, M T::*ptrmem)
{
return (*smartptr).*ptrmem;
}
现在一切都有一元运算符*
定义(迭代器,智能指针等)也可以使用 - > *
。您可能希望以更加受控制的方式执行此操作,即分别为已知迭代器,已知智能指针等定义它。
Now everything that has unary operator*
defined (iterators, smart pointers, whatever) can also use ->*
. You may want to do it in a bit more controlled fashion, i.e. define it for known iterators, known smart pointers etc. separately.
这对于成员函数不适用明显的原因。对于这种情况,需要专门化/重载并返回绑定的 std :: function
而不是:
This will not work for member functions for obvious reasons. One would need to specialize/overload for this case and return a bound std::function
instead:
template <typename P,
typename T,
typename M,
typename ... Arg>
std::function<M(Arg&&...)>
operator->* (P smartptr, M (T::*ptrmem)(Arg... args))
{
return [smartptr,ptrmem](Arg&&... args) -> M
{ return ((*smartptr).*ptrmem)(std::forward<Arg>(args)...); };
}
这篇关于类指针类和 - > *运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!